Header Ads

Exception Handling in JavaScript

How to Handle Error in JavaScript? In JavaScript there are four keywords to handle an error: 

How to Handle Error in JavaScript
1.TRY: The try statement allows you to define a block of code to be tested for errors while it being excuted.
try {
  // write some code here
  }
catch {
  //it will be excuted when some errors occur in the try block
  }
 
2.CATCH: The catch statement lets you handle the error. 

3.THROW: The throw statement allows you to create a custom error message. Means, if you are using throw statement with the custom message in the try block, then in the catch block err will be the custom message.
try {
  // write some code here
  }
catch(err) {
  //it will be excuted when some errors occur in the try block
  }
finally {
//it will excute all the time
}
 
4.FINALLY: The finally statement lets you excute code, after try and catch, regardless of the result. Means,finally doesn't care what's happening on the try and catch blocks .It will be excuted.
try {
  if(condition)throw "Custom Message"
  }
catch(err) {
  //here 'err' will be the custom message
  }
 

No comments:

Powered by Blogger.