[英]creating an exception handler in HTML5/javascript
我是Web開發領域的新手,我想迷失在Java腳本函數中創建異常的步驟中
我想要做的是遵循以下語法的事情...
function exceptionhandler (){
if (x===5)
{
//throw an exception
}
}
我發現以下教程http://www.sitepoint.com/exceptional-exception-handling-in-javascript/但我不知道如何將上述if語句轉換為try..catch ... finally異常
謝謝!
要在JavaScript中 創建錯誤,您必須throw
一些Error
,例如Error
, 特定類型的Error或任何Object或String 。
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
*/
您可能正在尋找這樣的東西:
function exceptionhandler() {
try {
if (x===5) {
// do something
}
} catch(ex) {
throw new Error("Boo! " + ex.message)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.