Javascript try catch statement

Created by
Wednesday, August 24, 2016

The try-catch Statement: In JavaScript, you need to write the code, where you can generate an error in the try block. Immediately after the try block, there is a catch block, which specifies the exception type that you want to catch. The syntax of the try-catch statement is as follows:

Try {  
    // code that can cause an error  
}  
Catch(err) {  
    // What to do when an error occurs  
}  

In the preceding syntax, there are two blocks: try and catch. The try block contains the suspected code, that can generate the errors. If the error occurs, the try block throws an exception, which is caught by each block. There is another optional block known as a finally block , which is associated with the try-catch statement. The syntax of the finally block is as follows.

Try {  
    // code that can use an error  
} catch (err) {  
    // what to do when an error occurs  
}  
Finally  
}  
// code that executes in all cases  
}  

The optional finally block of the try-catch statement always run its code, whether or not exceptions are thrown. If the code in the try block runs completely, the finally block executes. If there is an error, the catch block executes and then the finally block executes. Any time a control is about to return to the caller from inside a try or catch block through an explicit return statement, the finally block executes just before the control returns.

 

Tags:
javascript
js
0
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
0 comments