我是web开发领域的新手,我希望在java脚本函数中创建异常的步骤中迷失方向。
理想情况下,我想做的是遵循以下语法的东西...
function exceptionhandler (){
if (x===5)
{
//throw an exception
}
}我找到了下面的教程http://www.sitepoint.com/exceptional-exception-handling-in-javascript/,但我不知道如何将上面的if语句转换为try..catch...finally异常。
谢谢!
发布于 2013-02-15 02:40:36
要在JavaScript中创建一个错误,你必须创建一些东西,它可以是一个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
*/发布于 2013-02-15 02:39:38
你可能正在寻找类似这样的东西:
function exceptionhandler() {
try {
if (x===5) {
// do something
}
} catch(ex) {
throw new Error("Boo! " + ex.message)
}
}https://stackoverflow.com/questions/14881273
复制相似问题