5

If I have following

function ValidationException(nr, msg){
   this.message = msg;
   this.name = "my exception";
   this.number = nr;
}
function myFunction(dayOfWeek){
   if(dayOfWeek > 7){
      throw new ValidationException(dayOfWeek, "7days only!");
   }
}

Question is: How can I catch this particular exception in catch block?

Dave
  • 10,748
  • 3
  • 43
  • 54
user1765862
  • 13,635
  • 28
  • 115
  • 220

1 Answers1

9

JavaScript does not have a standardized way of catching different types of exceptions; however, you can do a general catch and then check the type in the catch. For example:

try {
    myFunction();
} catch (e) {
    if (e instanceof ValidationException) {
        // statements to handle ValidationException exceptions
    } else {
       // statements to handle any unspecified exceptions
       console.log(e); //generic error handling goes here
    }
}
Dave
  • 10,748
  • 3
  • 43
  • 54