[英]catching custom exception in js
如果我有以下
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塊中捕獲此特定異常?
JavaScript 沒有標准化的方法來捕獲不同類型的異常; 但是,你可以做一個一般的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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.