如果我有以下
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!");
}
}
问题是: 如何在catch块中捕获此特定异常?
答案 0 :(得分:7)
JavaScript does not have a standardized捕获不同类型异常的方法;但是,您可以执行常规catch
,然后检查catch
中的类型。例如:
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
}
}