Custom exception type

前端 未结 13 1702
生来不讨喜
生来不讨喜 2020-11-28 17:40

Can I define custom types for user-defined exceptions in JavaScript? If so, how would I do it?

13条回答
  •  时光取名叫无心
    2020-11-28 18:00

    You could implement your own exceptions and their handling for example like here:

    // define exceptions "classes" 
    function NotNumberException() {}
    function NotPositiveNumberException() {}
    
    // try some code
    try {
        // some function/code that can throw
        if (isNaN(value))
            throw new NotNumberException();
        else
        if (value < 0)
            throw new NotPositiveNumberException();
    }
    catch (e) {
        if (e instanceof NotNumberException) {
            alert("not a number");
        }
        else
        if (e instanceof NotPositiveNumberException) {
            alert("not a positive number");
        }
    }
    

    There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):

    // define exceptions "classes" 
    function NotNumberException() {}
    function NotPositiveNumberException() {}
    
    // try some code
    try {
        // some function/code that can throw
        if (isNaN(value))
            throw new NotNumberException();
        else
        if (value < 0)
            throw new NotPositiveNumberException();
    }
    catch (e if e instanceof NotNumberException) {
        alert("not a number");
    }
    catch (e if e instanceof NotPositiveNumberException) {
        alert("not a positive number");
    }
    

提交回复
热议问题