js抛出自定义异常

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

要说的就是在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!


  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值