javascript - 异常

疯狂的妞妞 / 2024-07-05 / 原文

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

    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);
        }
    }