Reputation: 14155
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?
Upvotes: 5
Views: 4906
Reputation: 10924
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
}
}
Upvotes: 9