Throw custom errors in JavaScript

Source code :

function MyError(message) {
  this.name = 'MyError';
  this.message = message || 'Cannot divide any number by 1';
  this.stack = (new Error()).stack;
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;

try {
  var val = 50;
    var div = 1 ;
    if( div ==1 ){
        throw new MyError();
    }else{
        var result = val/div;
         
    }
} catch (e) {
     alert(e.name);   
    alert(e.message);  
 }

Output :

MyError
Cannot divide any number by 1

Output :


                

Comments :