exception in js code example

Example 1: java define custom exception

public class CustomException extends Exception { 
    public CustomException(String errorMessage) {
        super(errorMessage);
    }
}

Example 2: 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 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 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>

Example 5: 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