四、try...catch...finally的变形
try…catch…finally语句有两种变形应用,即try…catch或者try…finally。
try…catch这种结构最常见,它的执行过程是:当没有例外发生执行完毕try块语句后或者发生例外执行完catch块语句后,控制将转移到整个try…catch结构后面的语句。请看下面的例子:
try { document.writeln("Beginnng the try block") document.writeln("No exceptions yet") // Create a syntax error eval("6 + * 3") document.writeln("Finished the try block with no exceptions") } catch(err) { document.writeln("Exception caught, executing the catch block") document.writeln("Error name: " + err.name) document.writeln("Error message: " + err.message) } document.writeln("Executing after the try-catch statement") |
如果是try…finally结构,那么当发生例外时,由于没有catch块语句来捕捉错误,所以最终finally块的语句也不会被执行。因此,这种结构在实际应用中很少见。
五、例外的表现形式:Error对象
在JavaScript,例外是作为Error对象出现的。Error对象有两个属性:name属性表示例外的类型,message属性表示例外的含义。根据这些属性的取值,我们可以决定处理例外的方式,比如:
function evalText() { try { alert(eval(prompt("Enter JavaScript to evaluate:",""))) } catch(err) { if(err.name == "SyntaxError") alert("Invalid expression") else alert("Cannot evaluate") } } |
上面的代码将对用户输入的内容进行表达式求值,然后显示出来。如果在求值过程中发生了SyntaxErroe类型错误,那么就会显示给用户“Invalid expression”的信息;否则,用户得到信息“Cannot evaluate”。
Error.name的取值一共有六种,如下:
EvalError:eval()的使用与定义不一致
RangeError:数值越界
ReferenceError:非法或不能识别的引用数值
SyntaxError:发生语法解析错误
TypeError:操作数类型错误
URIError:URI处理函数使用不当