javascript - 异常

如果偷懒,就这么干,要是没有很复杂的逻辑,不需要区分异常类型,这么写也没啥缺点。

    try {
        throw '参数未定义!';
    } catch (e) {
        console.error(e);
    }

ES5 语法

    /**
     * 非法输入参数异常
     */
    function IllegalArgumentException(message){
        this.message = message;
    }
    IllegalArgumentException.prototype = new Error();

    try {
        // 抛出一个异常
        throw new IllegalArgumentException('非法参数!');
    } catch (e) {
        if (e instanceof IllegalArgumentException) {
            console.error(e);
        }
    }

ES6 语法

    /**
     * 非法输入参数异常
     */
    class IllegalArgumentException extends Error {
        constructor(message) {
            super(message);
            Object.setPrototypeOf(this, IllegalArgumentException.prototype);
        }
    }

    try {
        // 抛出一个异常
        throw new IllegalArgumentException('非法参数!');
    } catch (e) {
        if (e instanceof IllegalArgumentException) {
            console.error(e);
        }
    }

posted on 2024-06-13 21:57  疯狂的妞妞  阅读(1)  评论(0编辑  收藏  举报

导航