Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

Error Handling in JavaScript Using try...catch

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 45

Error Handling in JavaScript Using try...catch

Post by admin » Tue Sep 03, 2019 2:08 pm

Error Handling in JavaScript Using try...catch

Here’s the basic syntax for try…catch:

Code: Select all

try {
  // some code that my error-out
} catch (e) {
  // this will run only if the code in the try block errors-out
}
Here’s an example where we misspell a variable name myNumber to yNumber:

Code: Select all

let myNumber = 2;
try {
  console.log(yNumber + 77);
} catch (e) {
  console.log('Oopsies -', e);
}
In this case, the catch block will be executed and the following message is printed to the console:

Oopsies - ReferenceError: yNumber is not defined

try…catch…finally
You can also tack-on a finally block to ensure that some code runs no matter if the code in the try blocks errors-out or not:

Code: Select all

let myVariable = 2;
try {
  console.log(myVriable + 77);
} catch (e) {
  console.log('Oopsies -', e);
} finally {
  console.log('Runs no matter what');
}
The finally block can be useful to clean-up your code

admin
Site Admin
Posts: 45

Post by admin » Sun Sep 08, 2019 8:23 pm

Good one

Post Reply