Javascript Try Catch Continue After Catch

Managing errors in js try catchJavaScript try catch statements are there for you to resolve any annoying errors that may pop up. Errors and bugs are part of programming, and they can be quite difficult to resolve. An error can be something small as forgetting a comma, which will leave you frustrated when trying to find where the problem is rooting from in the first place.

This article is for coders who want to handle errors and bugs effectively, so we will look at how the try catch in JavaScript function works.

Contents

  • Try Catch in JavaScript Explained: What Does It Mean
    • – The JavaScript Try Catch Parameters Overview
    • – Try Catch Finally Javascript Statement Description
    • – Properties of Errors in JavaScript
  • JavaScript Errors
    • 1. EvalError
    • 2. RangeError
    • 3. The syntaxError
    • 4. TypeError
    • 5. URI Error
    • 6. Throwing Errors and Error Constructors in JavaScript
  • Error Handling in JavaScript
    • – The Throw Statement
    • – Unconditional Catch-Block
    • – Conditional Catch-Blocks
    • – The Exception Identifier
    • – The Finally-Block
    • – Nesting Try Blocks
  • Examples
    • – Example 1
    • – Example 2
  • Conclusion

Try Catch in JavaScript Explained: What Does It Mean

The try catch in js marks a block of statements to attempt and specify a response should there be an exception.  The try catch block handles arising errors in JavaScript. You can use this statement if you do not want an error within your script to break your code.

Moreover, handling errors can be done with an if/else statement too; however, the try catch comes with much more benefits than what an if/else statement offer.

This is the syntax for it:

try {
try_statements
}
catch (exception_var) {
catch_statements
}
finally {
finally_statements

– The JavaScript Try Catch Parameters Overview

  • try_statements: this represents the statement to be executed.
  • catch_statements: it is the statement that is executed if an exception is thrown in the try-block.
  • exception_var: (optional) an identifier that holds an exception object for the associated catch block.
  • finally_statements: these are statements to be executed after the try statement completes execution. The try catch finally JavaScript statement will execute whether or not an exception was thrown or caught.

– Try Catch Finally Javascript Statement Description

The try statement has a try block containing one or more statements. Even for a single statement, you must use curly braces {}, and a finally-block, a catch block, or both must be present. Therefore, you will get three types of the try statement:

  • try…catch
  • try…finally
  • try…catch…finally

The catch block has statements that specify what you should do if you receive a JavaScript try catch exception. If an exception occurs from a statement within the try block or in a function called from within the try-block, control is immediately shifted to the catch block. Nonetheless, if no exception is thrown in the try-block, the catch-block is skipped.

The finally block always executes after the try block, and the catch blocks have finished executing. The finally block executes even when an exception is caught or thrown.

Nesting one or more try statements is possible. If the inner try statement lacks a catch-block, the statement that encloses the try statement catch-block is used instead. Also, if you want to handle JavaScript exceptions, the try statement can effectively handle them.

You can quickly test a code block with a try statement for errors. On the other hand, the catch statement allows you to handle the error that you find within your code.

How does it work? Just place your code in the try block within JavaScript, and if there is an error, JS will give catch statement control, and it will respond to whatever commands you have. Here, it alerts you to the error.

– Properties of Errors in JavaScript

Moreover, all errors in JavaScript are objects containing two properties:

  • The name, e.g., Error, syntaxError, etc.
  • The actual error message

Like other JavaScript objects, it is possible to access the values differently.

JavaScript Errors

The try/catch/finally statement handles errors (some or all) that occur in a block of code while still running code. In any case, we should explore each error individually in order to know how to handle it. So, errors can be programmer errors, errors arising from wrong input, and other unforeseeable things.

Typically, the errors in JavaScript are placed in six distinct categories:

1. EvalError

The EvalError represents an error in the eval() function. Although JavaScript no longer throws this exception, the EvalError object remains for backward compatibility with earlier versions.

2. RangeError

The RangeError object shows an error when a value is not within the set or range of allowed values. You can encounter this error in various circumstances:

  • When passing a value not allowed as one of the string values to the String.prototype.normalize()
  • When passing bad values to the numeric methods Number.prototype.toPrecision(), Number.prototype.toExponential(), or Number.prototype.toFixed().
  • When trying to create an array of illegal lengths with an array constructor

Its constructor is RangeError(), and it creates new RangeError object.

3. The syntaxError

The SyntaxError object shows an error when interpreting a syntactically invalid code. Moreover, JavaScript throws this error when the JavaScript engine encounters tokens or token order that does not conform to the language's syntax when parsing code.

Its constructor is SyntaxError(), creating a new SyntaxError object.

4. TypeError

The TypeError object means an error occurs when an operation could not be performed, typically when a value isn't of the expected type. This error appears in certain circumstances, such as:

  • When trying to adjust a value that cannot be changed
  • When trying to use a value inappropriately
  • When an argument or operand passed to a function is incompatible with the expected type by that function or operator.

Its constructor is TypeError(), i.e., it creates a new TypeError object.

5. URI Error

The URIError object means an error occurs when a global URI (Uniform Resource Identifier) handling function was not used correctly.

6. Throwing Errors and Error Constructors in JavaScript

Every JavaScript developer must have experienced errors a couple of times. For instance, you could easily throw an error like a new Error("Hi there").

Here, the word "error" represents Error, and the message is "Hi there". What's more, you can create a custom error constructor like this as well:

function CustomError(message){
this.value ="customError";
this.message=message;
}

Error Handling in JavaScript

To be effective at handling errors, you must understand what they mean. A try statement lets you define a block of code that you want to test for errors while it is still being executed. By contrast, a catch statement lets you define a code to be executed if errors occur in the try block. The finally statement allows the execution of the code after the try and catch statements regardless of the outcome.

Now, we invite you to look at the statements and blocks a little more closely below.

– The Throw Statement

The try catch statement can display a custom-created error, often called throw error. This is beneficial when you do not want JavaScript errors, as you can throw an exception (your own error) with the throw statement. The error can be a boolean, string, or object. If an error is present, the catch statement displays the error you throw.

Here is a coding example to make things clear:

throw "come tomorrow";            // throw a text

throw 200;          // throw a number

Using the throw statement alongside try and catch offers the flexibility to control the program flow and generate custom error messages.

Here is an elaborate example:

function getRectArea(height, width) {
if (isNaN(height) || isNaN(width)) {
throw 'Parameter is not a number!';
}
}
try {
getRectArea(6, 'D');
} catch (e) {
console.error(e);
// expected output: "Parameter is not a number!"

– Unconditional Catch-Block

The block is executed whenever an exception is thrown from within the block when using a catch block. If an exception occurs, control transfers to the catch block. The catch-block will specify an identifier holding the value of the exception. This value is available in the scope of the catch-block only.

Code example:

try {
throw 'myException'; // Produces an exception
} catch (e) {
// handles any exceptions
logMyErrors(e); // pass exception object to error handler
}

– Conditional Catch-Blocks

To create a conditional catch block, combine try catch blocks with the if/else if/else structures. While this seems a complicated approach, its common use is only to catch (and silence) a small subset of expected errors and then re-throw the error in other cases.

Code example:

try {
myroutine(); // might throw three exception types
} catch (e) {
if (e instanceof TypeError) {
// handles TypeError exceptions
} else if (e instanceof EvalError) {
// handles EvalError exceptions
} else if (e instanceof RangeError) {
// handles RangeError exceptions
} else {
// handles any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}

– The Exception Identifier

An exception can be thrown in a try block, and if that occurs, the exception_var, i.e., the "e" in catch(e), will hold the exception value. Use this identifier to obtain information about the thrown exception. Such an identifier is only found in the catch block's scope. However, it could be omitted if you do not need the exception value.

Code example:

function isValidJSON() {
try {
JSON.parse();
return true;
} catch {
return false;
}
}

– The Finally-Block

By now, you know that the finally block will execute after the catch and try blocks execute. However, it executes prior to performing the statements following the try…catch…finally block. Whether or not a code throws an exception, the finally block executes. Besides, if an exception is thrown, the statements within the finally block will execute if there is no catch block to handle the exception.

Code example:

openFile();
try {
// tie up a resource
writeFile(theData);
} finally {
closeFile(); // always close the resource
}

– Nesting Try Blocks

It is possible to nest try blocks; however, it can get clumsy and unbearable. Therefore, nesting try blocks are not highly recommended.

Nevertheless, nesting try blocks have the advantage of using a single cat statement for many statements. Still, you can opt to write catch statements for each try block as well.

Check out the code example below:

try {
try {
throw new Error('woow');
} finally {
console.log('finally');
}
} catch (ex) {
console.error('outer', ex.message);
}
// Output:
// "finally"
// "outer" "woow"
The addition of a catch-block, allows us to catch the exception in the inner try-block.
try {
try {
throw new Error('woow');
} catch (ex) {
console.error('inner', ex.message);
} finally {
console.log('finally');
}
} catch (ex) {
console.error('outer', ex.message);
}
// Output:
// "inner" "woow"
// "finally"
Now, rethrow the error:
try {
try {
throw new Error('woow');
} catch (ex) {
console.error('inner', ex.message);
throw ex;
} finally {
console.log('finally');
}
} catch (ex) {
console.error('outer', ex.message);
}
// Output:
// "inner" "woow"
// "finally"
// "outer" "woow"

An exception is only caught once by the nearest catch-block unless you rethrow it.

Examples

– Example 1

This example below misspells the word spellings:

<script>
try {
speddlings("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>

Output:

speddlings is not defined

JavaScript will catch spelling as an error and execute the catch code to handle it.

– Example 2

In this example we have an undefined value, "b," and so the catch block will be called, as you will see:

<script>
try{
var a= ["22″,"44″,"50″,"11″,"14″,"54″,"60"]; //a is an array
document.write(a);    // display elements of a
document.write(b); //b is undefined but still attempting to fetch its value. Thus the catch block will be called
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script>

Output:

Exception Handling22,44,50,11,14,54,60

Conclusion

In our JavaScript try catch article, we covered the following statements:

  • try{} statement – the try block keeps code that might require error testing. If there is an error, it passes it to the catch{} block
  • catch{} statement – it handles errors in a code by executing statements within the block. It has either a built-in handler or a user-defined exception handler, and it executes only error-prone codes
  • Throw Statement – used for throwing user-defined errors.
  • Try/catch statement can be written in three distinct ways: try…catch, try…finally, and try…catch…finally (try…catch…finally statements).
  • The finally statement is an optional block executed after the try and catch statements

Try catch in javascriptTo be creative at handling JavaScript errors, you must have a deeper understanding of the try…catch…finally statements and the throw statements in JavaScript. This review covers these topics in detail. Now, you can start creating functioning codes easily by employing these statements.

  • Author
  • Recent Posts

Position is Everything

wernerhicessell.blogspot.com

Source: https://www.positioniseverything.net/javascript-try-catch

0 Response to "Javascript Try Catch Continue After Catch"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel