您的位置:首页 > Web前端 > JavaScript

js抛出自定义异常

2016-07-28 15:34 716 查看
使用抛出异常机制能让代码结构更加的简洁,减少很多的逻辑判断,并且能够得到出错时的详细错误信息,可说是好处多多,今天

要说的就是在js中抛出(throw)异常。

js中可以抛出任何类型的异常,比如数字、字符串甚至布尔值,例如:

<script>
try {
throw 'error';
throw 123;
throw false;
}
catch (e) {
alert(e);
}
</script>

也可以抛出自定义的对象,比如:

<script>

function CommonException(message, code)
{
this.message = message;
this.code = code;
}

try
{
var exception = new CommonException('您的代码出错啦', 1);

throw exception;

alert('这地方的代码将不会执行到');
}
catch (e) {
alert(e.message);
alert(e.code)
}

</script>

当然,像大多数的面向对象语言中有内置的Exception类一样,js中也有内置的异常类: Error 

new Error([message[, fileName[, lineNumber]]])

message
Optional. Human-readable description of the error.
fileName
Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
lineNumber
Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.

 简单示例:
<script>
try {
throw new Error('Whoops!');
} catch (e) {
console.log(e.name + ': ' + e.message);
}
</script>

自定义异常类并继承Error基类:
<script>

// Create a new object, that prototypically inherits from the Error constructor
function MyError(message) {
this.name = 'MyError';
this.message = message || 'Default Message';
this.stack = (new Error()).stack;
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;

try {
throw new MyError();
} catch (e) {
console.log(e.name); // 'MyError'
console.log(e.message); // 'Default Message'
}

try {
throw new MyError('custom message');
} catch (e) {
console.log(e.name); // 'MyError'
console.log(e.message); // 'custom message'
}

</script>

除了Error基类,js中还内置了几种具体的异常类如下:

EvalError
Creates an instance representing an error that occurs regarding the global function eval().
InternalError
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError
Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError
Creates an instance representing a syntax error that occurs while parsing code in eval().
TypeError
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError
Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.

捕获处理特定的错误类

<script>

try {
//...;
} catch (e) {
if (e instanceof EvalError) {
console.log(e.name + ': ' + e.message);
} else if (e instanceof RangeError) {
console.log(e.name + ': ' + e.message);
} else if (e instanceof MyError)
{
console.log(e.name + ': ' + e.message);
} else {
// etc...
}
}

</script>

请参见:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/throw

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

That's it!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: