Try Catch and Finally in JavaScript is used for exception handling.
The try statement tests a block of code for errors. The catch statement handles the error.
The throw statement throws or creates custom errors. With final statement the code will be executed, and after try and catch, the function will return a result.
Errors will happen, when executing a code, and different errors can occur.
Error handling try and catch
In many times our scripts have errors. They are occurring because of programmer mistakes, unexpected user input, or something else.
Normally, a script immediately stops in case of an error, printing it as an error massage.
But there is a syntax construct try, catch that allows to catching errors and, instead of stop the program, do something with programmer custom massage.
The try statement consists of a try block, which contains one or more statements. {} always be used in try block.
One catch clause, or a finally clause, must be after try block to handle the error.
This gives three blocks for the try statement:
try, catch
try, finally
try, catch, finally
try and catch
The try
the statement allows creating a block of code for errors while it is being executed.
The catch
the statement allows creating a block of code to be executed, if there is any error occurs in the try block.
Syntax
1 2 3 4 5 6 | try { code to try } catch(error) { code to handle errors } |
OUTPUT
1 2 3 4 5 6 7 8 9 10 11 12 | <html> <body> <p id="jsdemo"></p> <script> try { adddlert("Welcome guest!"); } catch (err) { document.getElementById("jsdemo").innerHTML = err.message; } </script> </body> </html> |
OUTPUT
1 | adddlert is not defined |
The try, catch, finally Statement
Try catch finally are so called exception handling statements.
An exception is an error that occurs at run time due to an error operation during execution.
Examples of exceptions include trying to reference an undefined variable, or calling a nonexistent method.
Examples of syntax errors of exceptions:
• alert(“I am missing a closing part //syntax error
• alert(xy) //exception occur “xy” isn’t defined yet
• undefined function() //exception
Normally whenever runs an exception somewhere in code, it displays an error message to the user while aborting the execution of the remaining code.
At its simplest to use try/catch to try and run some code, and in the event of any exceptions,
User can catch programmer-generated and runtime exceptions, but cannot catch Js syntax errors.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <script type="text/javascript"> try { // Code to run } catch ( e ) { // Code to run if an exception occurs } finally { // Code that is always executed regardless of // an exception occurring } </script> |
The try block is followed by exactly one catch block or one finally.
When an exception occurs in the statement written inside try block, the control is transferred to the catch block.
In the catch block exception in caught in the object is declared in catch “err” and the catch block is executed.
The optional finally block executes after try/catch
If exception is thrown from try block then only catch block is executed.
Nested try/catch/finally statements
Try should never be defined just by itself, but always followed by catch or finally.
Within each clause, you can define additional try/catch/finally statements following the same rule.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <html> <body> <script> try { try { throw new Error('oops'); } finally { alert('Hi!'); } } catch (ex) { alert('There', ex.message); } </script> </body> </html> |
Caught the exception in the inner try-block by adding a catch block
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <html> <body> <script> try { try { throw new Error('oops'); } catch (ex) { alert('Hello', ex.message); } finally { alert('JS'); } } catch (ex) { alert('outer', ex.message); } </script> </body> </html> |
OUTPUT
1 2 | "Hello" "JS" |
Re-throw the error
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <html> <body> <script> try { try { throw new Error('oops'); } catch (ex) { alert('Hi', ex.message); throw ex; } finally { alert('JS'); } } catch (ex) { console.error('outer', ex.message); } </script> </body> </html> |
The throw Statement
throw statement to raise your built-in exceptions or customized exceptions. These exceptions can be captured and you can take an action.
The throw statement allows to create a custom error.
The exception can be a JS String, a Number, a Boolean or an Object:
throw “Too big”; // throw a text
throw 500; // throw a number
If programmer use throws together with try and catch, you can control program flow and generate custom error messages.
The finally Statement
The finally statement lets you execute code, after try and catch.
1 2 3 4 5 6 7 8 | try { code to try } catch (err) { code to handle errors } finally { code to be executed regardless of the try/catch result } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <html> <body> <p>Input a number between 5 and 20:</p> <input id="jsdemo" type="text"> <button type="button" onclick="checkRange()">check</button> <p id="info"></p> <script> function checkRange() { var message, x; message = document.getElementById("info"); message.innerHTML = ""; x = document.getElementById("jsdemo").value; try { if (x == "") throw "is empty"; if (isNaN(x)) throw "is not a number"; x = Number(x); if (x > 20) throw "is too high"; if (x < 5) throw "is too low"; } catch (err) { message.innerHTML = "Input " + err; } finally { document.getElementById("jsdemo").value = ""; } } </script> </body> </html> |
Here we discussed Try Catch and Finally in JavaScript. Hope you understand it.