try catch finally in javascript code example

Example 1: try catch in javascript

try {
  // Try to run this code 
}
catch(err) {
  // if any error, Code throws the error
}
finally {
  // Always run this code regardless of error or not
  //this block is optional
}

Example 2: try catch finally in javascript

try { // Try to run this code
  alert( 'try' ); 
  if (confirm('Make an error?')) BAD_CODE();
} catch (e) { // Code throws error
  alert( 'catch' );
} finally { // Always run this code regardless of error or not
  alert( 'finally' );
}

Example 3: try catch javascript

"The try...catch statement marks a block of statements to try and specifies"
"a response should an exception be thrown."

try {
  nonExistentFunction();
} catch (error) {
  console.error(error);
  // expected output: ReferenceError: nonExistentFunction is not defined
  // Note - error messages will vary depending on browser
}

Example 4: try catch finally in javascript

try {
  alert( 'try' );
  if (confirm('Make an error?')) BAD_CODE();
} catch (e) {
  alert( 'catch' );
} finally {
  alert( 'finally' );
}

Example 5: try catch javascript

try {

  alert('Start of try runs');  // (1) <--

  lalala; // error, variable is not defined!

  alert('End of try (never reached)');  // (2)

} catch(err) {

  alert(`Error has occurred!`); // (3) <--

}

Example 6: try catch throwing error in javascript

let json = '{ "age": 30 }'; // incomplete data

try {

  let user = JSON.parse(json); // <-- no errors
  alert( user.name ); // no name!

} catch (e) {
  alert( "doesn't execute" );
}

Tags:

Misc Example