gpt4 book ai didi

javascript - 在js中捕获自定义异常

转载 作者:行者123 更新时间:2023-12-04 01:49:31 25 4
gpt4 key购买 nike

如果我有以下

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 block 中捕获此特定异常?

最佳答案

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
}
}

关于javascript - 在js中捕获自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29422270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com