try and catch 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: javascript try

var someNumber = 1;
try {
  someNumber.replace("-",""); //You can't replace a int
} catch(err) {
 console.log(err);
}

Example 3: 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 4: catch javascript

//Catch is the method used when your promise has been rejected.
//It is executed immediately after a promise's reject method is called.
//Here’s the syntax:


myPromise.catch(error => {
  // do something with the error.
});

//error is the argument passed in to the reject method.

Example 5: js should i use try catch

One should avoid throw errors as the way to pass error conditions
around in applications.

The throw statement should only be used
"For this should never happen, crash and burn. Do not
recover elegantly in any way"

try catch however is used in situation where host objects
or ECMAScript may throw errors.

Example:
-------------------------------------
var json
try {
    json = JSON.parse(input)
} catch (e) {
    // invalid json input, set to null
    json = null
}
-------------------------------------

Example 6: 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
}

Tags: