[Javascript] Exception Handling with Try...Catch Block


In most of the programming language, Exception Handling is an integral part of it.  Every fellow developer must understand the concepts of exception handling(Try..catch) because it will help us to handle the run time exceptions.

The try...catch statement marks a block of statements to try, and specifies a response, should an exception be thrown.

The first step in constructing an Exception Handler is to enclose the code that might possibly throw a runtime exception within a try block. In general, a try block looks like the following:

try {
    try statement.
}
catch and finally blocks . . .

In the above code segment, try statement section might contain one or more illegal statement that might throw an exception. By enclosing these statements within the try block, we can avoid the application crash.

Syntax

try {
   Try Block
}
[catch (Exception) {
   Catch Block
}]
[finally {
   Finally Block
}]

Catch Block

Statements that are executed if an exception is thrown in the try block. if try block succeeds then control won't be passed to the catch block. if try block didn't succeed then control will be moved to catch clause.

Exception

An identifier to hold an exception object for the associated catch clause. This exception object contains details about the type of exception thrown from the try block.

Finally Block

Statements that are executed after the try statement completes. These statements execute regardless of whether or not an exception was thrown or caught. If Exception is caught after catch block, finally block will be executed.

if try block is used, at-least one catch clause or finally clause or both must be present. There are three different forms, try catch statements will be used.
  • try...catch
  • try...finally
  • try...catch...finally
Examples:

1. try...catch

openMyFile();
try {
   writeMyFile(theData);
}
catch (e) {
   // statements to handle any exceptions
   logMyErrors(e); // pass exception object to error handler
}

2. try...finally

openMyFile();
try {
   writeMyFile(theData);
}
finally {
   closeMyFile(); // always close the resource
}

3. try...catch...finally

openMyFile();
try {
   writeMyFile(theData);
}
catch (e) {
   logMyErrors(e); 
}finally {
   closeMyFile();
}

Unconditional catch clause

Single catch statement is present, Irrespective of any exception, the catch clause will be executed.

try {
   routine();
}
catch (e) {
   // statements to handle any exceptions
   logMyErrors(e); // pass exception object to error handler
}

Conditional catch clauses

We will have one or more multiple catch clause to handle the specific exception. In the below example routine() method potentially might throw TypeError, RangeError or EvalError and we have specific catch clause for each error. 


Multiple catch statement: 

try {
    routine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
    // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
    // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
    // statements to handle EvalError exceptions
} catch (e) {
    // statements to handle any unspecified exceptions
    logMyErrors(e); // pass exception object to error handler
}

Note: This functionality is not part of the ECMAScript specification. However, you can implement the above functionality as mentioned below

Single catch block with multiple conditions:

try {
    routine(); // may throw three types of exceptions
} catch (e) {
    if (e instanceof TypeError) {
        // statements to handle TypeError exceptions
    } else if (e instanceof RangeError) {
        // statements to handle RangeError exceptions
    } else if (e instanceof EvalError) {
        // statements to handle EvalError exceptions
    } else {
       // statements to handle any unspecified exceptions
       logMyErrors(e); // pass exception object to error handler
    }
}

Finally clause:

The finally clause contains statements to execute after the try block and catch clause(s) execute. Finally clause will execute irrespective of error is thrown or not.

openMyFile();
try {
   writeMyFile(theData);
}
finally {
   closeMyFile(); // always close the resource


}

Nested Try Block:

Nested Try Block is also possible with Javascript. Find the example below.

try {
  try {
  Potentially error code;
   }
  finally {
    console.log('finally');
  }
}
catch (ex) {
  console.error('outer');
}

// Output:
// "finally"
// "outer" 

This post is mainly based on MDN Documentation.




If you enjoyed this article, Please share it with your developer friends and in social media. 
Follow our facebook page for latest updates.

Comments

  1. Thanks for posting this :). I wish exception filters/pattern matching would become part of the spec! I work on the following open source project for error logging ( https://github.com/exceptionless/Exceptionless.JavaScript ) and it would be really nice to do conditional logging in a catch block.

    ReplyDelete

Post a Comment