[译]Javascript中的错误信息处理(Error handling)
Posted 马大欧
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[译]Javascript中的错误信息处理(Error handling)相关的知识,希望对你有一定的参考价值。
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单
源地址在此:
https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b
在Javascript中使用try/catch/finally来处理runtime的错误.这些runtime错误被称为exceptions.各种各样的原因都可能导致exception.比如,使用没有申明的变量或者方法都可能导致exception.
可能导致exceptions的Javascript语句都应该被包裹在try语句内.当try语句内的某一句导致exception的时候,控制权就立刻转移到catch语句内,然后跳过try语句内的剩下所有代码内容.
Javascript try catch例子:
try { // Referencing a function that does not exist cause an exception // 使用不存在的函数导致产生一个exception document.write(sayHello()); // Since the above line causes an exception, the following line will not be executed // 因为以上的代码导致出现exception,所以这以下的代码将不会运行
document.write("This line will not be executed"); } // When an exception occurs, the control is transferred to the catch block //当exception产生后,控制权就转交到了catch语句块中
catch (e) { document.write("Description = " + e.description + "[br/]"); document.write("Message = " + e.message + "[br/]"); document.write("Stack = " + e.stack + "[br/][br/]"); } document.write("This line will be executed");
Output : // JavaScript try catch example.png
请注意:一个try语句块应该始终紧跟一个catch语句块或者一个finally语句块,或者两者兼有
finally语句块无论exception是否产生都会运行.其主要用处在于清理和释放脚本运行期间所占用的资源.举个例子,如果你的try语句块打开了一个文件且运行,而好死不死又发生了一个exception,那么finally语句块就是用来关闭文件的.
Javascript try catch finally例子:
try { // Referencing a function that does not exist cause an exception document.write(sayHello()); // Since the above line causes an exception, the following line will not be executed document.write("This line will not be executed"); } // When an exception occurs, the control is transferred to the catch block catch (e) { document.write("Description = " + e.description + "[br/]"); document.write("Message = " + e.message + "[br/]"); document.write("Stack = " + e.stack + "[br/][br/]"); } finally { document.write("This line is guaranteed to execute"); }
Output : JavaScript try catch finally example.png
Javascript中的格式错误与exceptions需要注意的是:
try/catch/finally语句块可以捕捉到exceptions,但是格式错误则无法被其捕捉到.
例子:以下代码中有一个格式错误-丢失了闭小括号.catch语句块则无法捕捉到这个错误
try { alert("Hello"; } catch (e) { document.write("JavaScript syntax errors cannot be caught in the catch block"); }
Javascript throw语句:用throw语句来捕捉自定义exceptions
Javascript throw exception例子:
JavaScript throw exception example : function divide() { var numerator = Number(prompt("Enter numerator")); var denominator = Number(prompt("Enter denominator")); try { if (denominator == 0) { throw { error: "Divide by zero error", message: "Denominator cannot be zero" }; } else { alert("Result = " + (numerator / denominator)); } } catch (e) { document.write(e.error + "[br/]"); document.write(e.message + "[br/]"); } } divide();
以上是关于[译]Javascript中的错误信息处理(Error handling)的主要内容,如果未能解决你的问题,请参考以下文章