是否有可能在J中使用多个catch,S(ES5 or ES6)就像我在下面描述的那样(仅作为示例):
try {
// just an error
throw 1;
}
catch(e if e instanceof ReferenceError) {
// here i would like to manage errors which is 'undefined' type
}
catch(e if typeof e === "string") {
// here i can manage all string exeptions
}
// and so on and so on
catch(e) {
// and finally here i can manage another exeptions
}
finally {
// and a simple finally block
}
Run Code Online (Sandbox Code Playgroud)
这与我们C#在a或a中的相同Java.
提前致谢!
以这种方式尝试:
try {
throw 1;
}
catch(e) {
if (e instanceof ReferenceError) {
// ReferenceError action here
} else if (typeof e === "string") {
// error as a string action here
} else {
// General error here
}
}
finally {}
Run Code Online (Sandbox Code Playgroud)
当然,多个 if/then/else 绝对没有错,但我从不喜欢它的外观。我发现当所有东西都排列好时,我的眼睛浏览得更快,所以我改用切换方法来帮助我浏览/寻找正确的块。{}既然 ES6let命令已经流行起来,我也开始使用词法范围来包含 case 块。
try {
// OOPS!
} catch (error) {
switch (true) {
case (error instanceof ForbiddenError): {
// be mean and gruff;
break;
}
case (error instanceof UserError): {
// be nice;
break;
}
default: {
// log, cuz this is weird;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9945 次 |
| 最近记录: |