js exception 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: catch error message js

try {
  // test code
} catch (error) { // if error
  console.error(error); // return error
}

Example 3: exception js

function div(){
    let x = prompt('Entrez un premier nombre (numérateur)');
    let y = prompt('Entrez un deuxième nombre (dénominateur)');
    
    if(isNaN(x) || isNaN(y) || x == '' || y == ''){
        throw new Error('Merci de rentrer deux nombres');
    }else if(y == 0){
         throw new Error('Division par 0 impossible')
    }else{
        alert(x / y);
    }
}

try{
    div();
}catch(err){
    alert(err.message);
}finally{
    alert('Ce message s\'affichera quoiqu\'il arrive');
}

Example 4: javascript how to raise the error

if (..condition..) {
    throw 'Error message';
  }

Example 5: javascript try

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

Example 6: js throw custom error

class CustomError extends Error {
  constructor(foo = 'bar', ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params)

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError)
    }

    this.name = 'CustomError'
    // Custom debugging information
    this.foo = foo
    this.date = new Date()
  }
}

try {
  throw new CustomError('baz', 'bazMessage')
} catch(e) {
  console.error(e.name)    //CustomError
  console.error(e.foo)     //baz
  console.error(e.message) //bazMessage
  console.error(e.stack)   //stacktrace
}