JavaScript try-catch-finally Statement

JavaScript try-catch-finally Statement


JavaScript try/catch/finally Statement
In this tutorial, you will learn about try…catch…finally Statement in JavaScript with the help of examples:
Exception Handling In JavaScript:
  • Ever since the beginning of programming languages, error handling has been a particularly difficult issue.
  • Exception handling wires error handling directly into the programming language and sometimes even the operating system.
  • An exception is an object that is “thrown” from the site of the error and can be “caught” by an appropriate exception handler designed to handle that particular type of error.
Exception Handling key Points
  • Use try and catch
  • Know the members of Throwable
  • Use finally
  • Java exception handling is managed via five keywords: try, catch, throw, and finally.
  • Briefly, here is how they work. Program statements that you want to monitor for exceptions are contained within a try block.
  • If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner.
  • System-generated exceptions are automatically thrown by the Java run-time system.
  • To manually throw an exception, use the keyword throw.
  • Any exception that is thrown out of a method must be specified as such by a throws clause.
  • Any code that absolutely must be executed after a try block completes is put in a finally block.
 
The Syntax of the try…catch…finally Statement in JavaScript is as follows:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Example 1 -
Output -
Example 2 -
 
Output -