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!
要说的就是在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!
相关文章推荐
- javascript 引用类型 - 内置对象(Math对象)
- javascript 引用类型 - 基本包装类型(深入理解基本包装类型和基本类型的区别)
- js需要把时间戳转为为普通格式
- javascript-由初速度和仰角求射程
- Extjs的GridPanel分页前后台完整代码实例
- 反序列化Json
- js中关于this的理解
- JS 省市两级联动(不带地区版本)
- Javascript数组Array的forEach方法
- javascript数组与字符串的相互转化
- Json解析工具Jackson(使用注解)
- jvm系列(四):jvm调优-命令大全(jps jstat jmap jhat jstack jinfo)
- 关于JavaScript测试工具:QUnit, Jasmine, MoCha
- javascript定义函数问题
- js 去除字符串两边的空格
- controller层响应客户端json数据
- controller层响应客户端json数据
- controller层响应客户端json数据
- ES6学习-let和const
- jsp技术:day1--jsp简单用法、静态导入、动态导入、设置errorPage、<jsp:forward>