Understanding Try Catch Finally JavaScript

JavaScript , , 0 Comments

In this article, we will learn about all three clauses of try catch finally in JavaScript with examples that will cover almost all cases.

The try...catch statement consists of a try block, which contains one or more statements. The body {} of try...catch statement is required and must always be used, even for single statements. At least one catch clause, or a finally clause, must be present with try clause. So basically we have three forms of try...catch statement:

  1. try...catch
  2. try...finally
  3. try...catch...finally

catch clause contains statements that specify what to do if an exception is thrown in the try block.

And in sort, the finally clause will be executed after, when try clause will run or catch clause will run.

Syntax

try {
  try_statements
}
[catch (exception_var_1 if condition_1) { // non-standard
  catch_statements_1
}]
...
[catch (exception_var_2) {
  catch_statements_2
}]
[finally {
  finally_statements
}]

try_statements:- The statements to be executed.

catch_statements_1, catch_statements_2:- These statements will run if there is an error/exception will occur in the try block.

exception_var_1, exception_var_2:- These are the identifiers to hold an exception object for the associated catch clause.

condition_1:- A conditional expression.

finally_statements:- As I already told you the finally clause will be executed after when try clause will run or catch clause will run. These statements execute regardless of whether an exception was thrown or caught. You can say that the finally statement always executes.

#1 Unconditional catch clause

try catch finally in JavaScript has an Unconditional catch clause statement is a simple catch statement that catches the exception object. For example below

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

In the above example, we simply thrown an exception in the try block and received it inside the catch block and passed to the custom error handler called logMyErrors.

Note: you can take any name you like instead of e

#2 Conditional catch clauses

You can easily use one or more conditionally catch statements with try to detect the specific type of error/exception. The try block can potentially throw three types of exceptions: TypeErrorRangeError, and EvalError.

For example below:-

Note: this functionality is not part of the ECMAScript specification and has been removed in Firefox 59. It’s not supported in any current browser anymore.

try {
  myroutine(); // 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
}

As per MDN

Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Here is the same alternative working examples: (obviously it’s verbose, but works everywhere):

try {
  myroutine(); // 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
  }
}

#3 The finally clause

The finally clause (oh please you know the finally clause I already told you two times before ūüėÄ ), will be executed after when try clause will run or catch clause will run. But Note that the finally clause executes regardless of whether an exception is thrown.

You can use the finally clause to clear up things anyway or general/routine cleanups. For example:-

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

#4 Nested try-blocks

Yes, you can also use nesting with try...catch

try {
  try {
    throw new Error('oops');
  }
  finally {
    console.log('finally');
  }
}
catch (ex) {
  console.error('outer', ex.message);
}

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

See? In the above example, we did not define the catch block with the inner try block, so the outer catch block gets the exception. Let’s see the example if we put the catch inside. For example below

#4.1 Inner Catch

try {
  try {
    throw new Error('oops');
  }
  catch (ex) {
    console.error('inner', ex.message);
  }
  finally {
    console.log('finally');
  }
}
catch (ex) {
  console.error('outer', ex.message);
}

// Output:
// "inner" "oops"
// "finally"

Did you noticed how the inner catch gets the error, Let’s see what if we re-throw the error inside the inner catch for example below:-

#4.1 Re-Throwing nested exception.

try {
  try {
    throw new Error('oops');
  }
  catch (ex) {
    console.error('inner', ex.message);
    throw ex;
  }
  finally {
    console.log('finally');
  }
}
catch (ex) {
  console.error('outer', ex.message);
}

// Output:
// "inner" "oops"
// "finally"
// "outer" "oops"

See It proves that any given error/exception will be caught only once by the nearest enclosing catch block unless it is re-thrown.¬†Of course, any new error/exception occurs in the ‘Inner’ block with be caught by the “outer” block because maybe the code inside ‘Inner’ block will do something wrong and throw an error.

#5 Returning from finally

You can also return from the finally block, understand try catch finally in JavaScript with an example below:-

(function() {
  try {
    try {
      throw new Error('oops');
    }
    catch (ex) {
      console.error('inner', ex.message);
      throw ex;
    }
    finally {
      console.log('finally');
      return;
    }
  }
  catch (ex) {
    console.error('outer', ex.message);
  }
})();

// Output:
// "inner" "oops"
// "finally"

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any return statements in the try and catch blocks. 

Browser Support

Statement
try/catch/finallyYesYesYesYesYes

If you want to learn about New try catch Optional catch binding update in ES10/2019 Click here

That’s all for the try…catch. Thanks for reading and sorry for this long article I don’t even have a meme for you. please share it with love.

Spread the love

Leave a Reply

avatar
  Subscribe  
Notify of