js 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 try catch

<html>  
<head>Exception Handling</head>  
<body>  
<script>  
try {  
   throw new Error('This is the throw keyword'); //user-defined throw statement.  
}  
catch (e) {  
  document.write(e.message); // This will generate an error message  
}  
</script>  
</body>  
</html>