JS-断言与错误处理

<script type="text/javascript">
    function assert(condition, message){
        if (!condition){
            throw new Error(message);
        }
    }
    function divide(num1, num2){
        assert(typeof num1 == "number" && typeof num2 == "number",
               "divide(): Both arguments must be numbers.");
        return num1 / num2;
    }
    var result = divide(10, 23);
    result = divide("hi", 3);
</script>

错误: Error 为全局对象

<body>
    <script type="text/javascript">
        window.onerror = function(message, url, line){
            alert(message);
            return false;
        };
        throw new Error("Something bad happened.");
    </script>
</body>

通过原型链的继承 - 实现自定义错误

<script type="text/javascript">
    function CustomError(message){
        this.name = "CustomError";
        this.message = message;
    }
    CustomError.prototype = new Error();
    function process(values){
        if (!(values instanceof Array)){
            throw new CustomError("process(): Argument must be an array.");
        }
        values.sort();
        for (var i=0, len=values.length; i < len; i++){
            if (values[i] > 100){
                return values[i];
            }
        }
        return -1;
    }
    process("string");
</script>

try{...}catch{...}finally{...} 捕获异常

<script type="text/javascript">
    try {
        window.someNonexistentFunction();
    } catch (error){
        alert(error.name);
        alert(error.message);
    }
</script>
<body>
    <script type="text/javascript">
        function testFinally(){
            try {
                return 2;
            } catch (error){
                return 1;
            } finally { 
// 有 finally 之后,返回的值就是 finally 里面的
// 如果 finally 里没 return 调用,则返回上一个 return 的值
                return 0;
            }
        }
        function testWithoutFinally(){
            try {
                return 2;
            } catch (error){
                return 1;
            }
        }
        alert(testFinally()); // 0
        alert(testWithoutFinally()); // 2
    </script>
</body>