javascript exceptions 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: 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 3: javascript how to raise the error

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

Example 4: javascript try

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

Example 5: try catch error

try {
console.log('hello');
}
catch (e){
}