我是Web开发世界的新手,我希望在java脚本函数中创建异常的步骤中迷失方向
我想要理想的做法是遵循以下语法......
function exceptionhandler (){
if (x===5)
{
//throw an exception
}
}
我找到了以下教程 http://www.sitepoint.com/exceptional-exception-handling-in-javascript/ 但我不知道如何将上面的if语句转换为try..catch ... finally异常
谢谢!
答案 0 :(得分:3)
要创建 JavaScript 中的错误,您必须throw
某事,可以是Error
,specific type 错误,或任何对象或字符串。
function five_is_bad(x) {
if (x===5) {
// `x` should never be 5! Throw an error!
throw new RangeError('Input was 5!');
}
return x;
}
console.log('a');
try {
console.log('b');
five_is_bad(5); // error thrown in this function so this
// line causes entry into catch
console.log('c'); // this line doesn't execute if exception in `five_is_bad`
} catch (ex) {
// this only happens if there was an exception in the `try`
console.log('in catch with', ex, '[' + ex.message + ']');
} finally {
// this happens either way
console.log('d');
}
console.log('e');
/*
a
b
in catch with RangeError {} [Input was 5!]
d
e
*/
答案 1 :(得分:0)
你可能正在寻找这样的东西:
function exceptionhandler() {
try {
if (x===5) {
// do something
}
} catch(ex) {
throw new Error("Boo! " + ex.message)
}
}