Javascript 简明教程

JavaScript - Errors & Exceptions Handling

JavaScript 中的错误处理是检测和处理在程序执行期间发生的错误的一个过程。错误可以是语法错误、运行时错误或逻辑错误。在程序执行期间发生的错误称为运行时错误(异常)。

Error handling in JavaScript is a process to detect and handle errors that occurs during the execution of a program. Errors can be a syntax, runtime or logical errors. An error occurred during the execution of the program is called a runtime error or an exception.

在 JavaScript 中,错误可能因为编程错误、错误的用户输入等而发生。错误可能中断代码执行并导致用户体验不佳。构建强大、可靠且用户友好的 JavaScript 应用程序需要有效的错误和异常处理。

In JavaScript, errors can occur due to programming mistakes, incorrect user input, etc. Errors can disrupt code execution and lead to bad user experience. Effective error & exception handling is required for building robust, reliable and user friendly applications in JavaScript.

What is an Error?

错误是程序执行期间发生的事件,该事件阻止了程序正常继续运行。错误可能是由于各种因素引起的,例如 syntax 错误、 runtime 错误和 logical 错误。

An error is an event that occurs during the execution of a program that prevents it from continuing normally. Errors can be caused by a variety of factors, such as syntax errors, runtime errors, and logical errors.

Syntax Errors

语法错误又称 parsing errors ,发生在传统编程语言编译时以及 JavaScript 解释时。

Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript.

例如,以下行会引发语法错误,因为它缺少一个结束括号。

For example, the following line causes a syntax error because it is missing a closing parenthesis.

<script>
   window.print();
</script>

当 JavaScript 中发生语法错误时,只有包含在与语法错误相同的线程中的代码会受到影响,而其他线程中的其余代码会继续执行,假定其中的任何内容都不依赖包含该错误的代码。

When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected, and the rest of the code in other threads gets executed, assuming nothing in them depends on the code containing the error.

Runtime Errors (Exceptions)

运行时错误又称 exceptions ,发生在执行期间(编译/解释之后)。

Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).

例如,以下行会引发运行时错误,因为这里的语法是正确的,但在运行时它试图调用一个不存在的方法。

For example, the following line causes a runtime error because the syntax is correct here, but at runtime, it is trying to call a method that does not exist.

<script>
   window.printme();
</script>

异常也会影响它们发生的线程,允许其他 JavaScript 线程继续正常执行。

Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.

有许多 JavaScript 运行时错误(异常),其中一些如下所示 −

There are many JavaScript runtime errors (exceptions), some are as follows −

  1. ReferenceError − Trying to access an undefined variable/ method.

  2. TypeError − Attempting an operation on incompatible data types.

  3. RangeError − A value exceeds the allowed range.

Logical Errors

逻辑错误可能是最难追踪的错误类型。这些错误不是语法或运行时错误的结果。它们在你编写脚本时,在驱动脚本的逻辑中犯了错误但未获得预期结果时发生。

Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and do not get the expected result.

例如,当你将任何数字值除以 10 时,它将返回未定义。

For example, when you divide any numeric value with 10, it returns undefined.

<script>
   let num = 10/0;
</script>

What is Error Handling?

每当在 JavaScript 代码中发生任何错误时,JavaScript 引擎就会停止执行整个代码。如果你以正确的方式处理此类错误,你可以跳过带有错误的代码,并继续执行其他 JavaScript 代码。

Whenever any error occurs in the JavaScript code, the JavaScript engine stops the execution of the whole code. If you handle such errors in the proper way, you can skip the code with errors and continue to execute the other JavaScript code.

你可以使用以下机制来处理错误。

You can use the following mechanisms to handle the error.

  1. try…​catch…​finally statements

  2. throw statements

  3. the onerror() event handler property

  4. Custom Errors

The try…​catch…​finally Statement

最新版本的 JavaScript 增加了异常处理功能。JavaScript 实现了 try…​catch…​finally 结构以及 throw 运算符来处理异常。

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try…​catch…​finally construct as well as the throw operator to handle exceptions.

你可以捕获程序员生成的和运行时异常,但你无法捕获 JavaScript 语法错误。

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

以下是 try…​catch…​finally 块语法 −

Here is the try…​catch…​finally block syntax −

<script>
   try {
      // Code to run
      [break;]
   }
   catch ( e ) {
      // Code to run if an exception occurs
      [break;]
   }
   [ finally {
      // Code that is always executed regardless of
      // an exception occurring
   }]
</script>

try 块必须紧跟一个 catch 块或一个 finally 块(或两者之一)。当在 try 块中发生异常时,异常将被放入 e 中并且 catch 块将被执行。可选的 finally 块在 try/catch 之后无条件执行。

The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.

Example

下面是一个示例,其中我们尝试调用一个不存在的函数,它又会引发一个异常。

Here is an example where we are trying to call a non-existing function which in turn is raising an exception.

让我们尝试使用 try…​catch 来捕获这个异常,并显示一条用户友好的消息。如果你想向用户隐藏此错误,你也可以禁止此消息。

Let us try to catch this exception using try…​catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from a user.

你可以使用 finally 块,该块将在 try/catch 之后始终无条件执行。

You can use finally block which will always execute unconditionally after the try/catch.

<html>
<head>
<script>
   try {
      var a = 100;
      alert(myFunc(a));
   }
   catch (e) {
      alert(e);
   }
   finally {
      alert("Finally block will always execute!" );
   }
</script>
</head>
<body>
   <p>Exception handling using try...catch...finally statements</p>
</body>
</html>
Exception handling using try...catch...finaly statements

The throw Statement

你可以使用 throw 语句引发内置异常或自定义异常。之后可以捕获这些异常,你可以采取适当的操作。

You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.

Example

以下示例演示如何使用 throw 语句。

The following example demonstrates how to use a throw statement.

<html>
<head>
<script>
   function myFunc() {
      var a = 100;
      var b = 0;

      try {
         if ( b == 0 ) {
            throw( "Divide by zero error." );
         } else {
            var c = a / b;
         }
      }
      catch ( e ) {
         alert("Error: " + e );
      }
   }
</script>
</head>
<body>
   <p>Click the following to see the result:</p>
   <form>
      <input type = "button" value = "Click Me" onclick = "myFunc();" />
   </form>
</body>
</html>
Click the following to see the result:
Click Me

你可以在一个函数中使用一个字符串、整数、布尔值或一个对象引发一个异常,然后你可以在与上面相同的一个函数中捕获该异常,或在使用 try…​catch 块的另一个函数中捕获。

You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in the same function as we did above, or in another function using a try…​catch block.

The onerror Event Handler Property

onerror 事件处理程序是促进在 JavaScript 中错误处理的第一个功能。onerror 是“window”对象的事件处理程序属性,当在网页的任何元素上发生任何错误时,它将自动触发。当出现任何错误时,你可以调用回调函数来处理错误。

The onerror event handler was the first feature to facilitate error handling in JavaScript. The onerror is an event handler property of the 'window' object, which automatically triggers when any error occurs on any element of the web page. You can call the callback function when any error occurs to handle the error.

您可以遵循以下语法来使用 onerror 事件处理程序属性。

You can follow the syntax below to use the onerror event handler property.

window.onerror = errorhandler_func;
OR
<ele onerror="errorhandler_func()"> </ele>

在上述语法中,只要发生任何错误,都将执行 errorhandler_func()。

In the above syntax, errorhandler_func() will be executed when any error will occur.

onerror 事件处理程序提供三项信息来识别错误的确切性质 −

The onerror event handler provides three pieces of information to identify the exact nature of the error −

  1. Error message − The same message that the browser would display for the given error

  2. URL − The file in which the error occurred

  3. Line number − The line number in the given URL that caused the error

Example

在下面的代码中,我们向 <input> 元素添加了 onclick 事件,并且我们在用户单击输入元素时调用 myFunc() 函数。myFunc() 函数未定义。因此,它将引发错误。

In the code below, we added the onclick event on the <input> element, and we called the myFunc() function when users click the input element. The myFunc() function is not defined. So, it will throw an error.

我们使用 'onerror' 事件处理程序来捕捉错误。在回调函数中,我们在错误发生的文件中打印错误消息、文件 URL 和行号。

We used the 'onerror' event handler to catch the error. In the callback function, we print the error message, file URL, and line number in the file where the error occurs.

<html>
<body>
   <p> Click the following button to see the result:</p>
   <form>
      <input type = "button" value = "Click Me" onclick = "myFunc();" />
   </form>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      window.onerror = function (msg, url, line) {
         output.innerHTML = "Error: " + msg + "<br>";
         output.innerHTML += "URL: " + url + "<br>";
         output.innerHTML += "Line: " + line + "<br>";
      }
   </script>
</body>
</html>

Output

Click the following button to see the result:
Click Me
Error: Uncaught ReferenceError: myFunc is not defined
URL: file:///C:/Users/Lenovo/Desktop/intex.html
Line: 5

您可以使用 onerror 方法(如下所示)在加载图像时出现任何问题时显示错误消息。

You can use an onerror method, as shown below, to display an error message in case there is any problem in loading an image.

<img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />

您可以将 onerror 与多个 HTML 标记一起使用,以便在发生错误时显示适当的消息。

You can use onerror with many HTML tags to display appropriate messages in case of errors.

The JavaScript Error Class and Error Object

无论何时代码中发生任何错误,JavaScript 都会抛出错误类的一个实例(对象)。错误对象包含有关错误的信息。

Whenever any error occurs in the code, JavaScript throws an instance (object) of the error class. The error object contains the information about the error.

但是,Error() 是针对所有类型错误的通用构造函数,但针对不同类型的错误存在不同的对象。

However, Error() is a generic constructor for all types of errors, but different objects exist for different types of errors.

JavaScript Custom Errors

您还可以使用 Error() 构造函数抛出一个带有自定义消息的错误。

You can also throw an error with the custom message using the Error() constructor.

const customError = new Error(message);
customError.name = "CustomError";

此处,我们创建了“Error”类实例并传递了“message”作为参数。此外,我们更改了“name”属性的值。同样,如果你不想将“message”属性作为 Error() 构造函数的参数传递,则可以更改“message”属性的值。

Here, we have created the 'Error' class instance and passed the 'message' as an argument. Also, we have changed the value of the 'name' property. Similarly, you can change the value of the 'message' property if you don’t want to pass it as an Error() constructor argument.

JavaScript Error Object Reference

JavaScript Error Types or Constructor

JavaScript 包含以下类型的错误。您还可以将其用作构造函数来创建特定类型的新错误。

JavaScript contains the below types of errors. You can also use it as a constructor to create a new error of the specific type.

Error Type/Object

Description

Error

It is a generic constructor for the error. You can also create custom errors by extending the Error object.

SyntaxError

The instance of the SyntaxError is thrown when any error is in the syntax. For example, missing parenthesis, invalid JSON, etc.

ReferenceError

The reference error occurs when you try to access variables not defined in the current scope.

TypeError

When the types of the variables is not valid, JavaScript throws the type error.

RangeError

When numeric input is out of range, it throws the range error.

URIError

JavaScript throws the URIError when you pass invalid arguments to the decodeURI or encodeURI methods.

EvalError

Deprecated.

AggregateError

It is used to aggregate multiple error objects into a single error object, and it allows you to handle multiple error objects.

Error Object Properties

Error 对象包含两个属性。

The Error object contains the two properties.

Property

Description

name

It is used to set or get an error name.

message

It is used to set or get an error message.

Non-Standard Properties and Methods

以下是 Error 对象的非标准属性和方法列表。但是,并非所有浏览器都支持它们。因此,应避免使用它们。

Here is the list of the non-standard properties and methods of the Error object. However, they are not supported by all browsers. So, you should avoid using them.

Property

Description

columnNumber

It is supported in the Firefox browser only.

description

It is supported in the Microsoft browser only.

displayName

It is supported in the Firefox browser only.

fileName

It is supported in the Firefox browser only.

lineNumber

It is supported in the Firefox browser only.

number

It is supported in the Microsoft browser only.

stack

It is supported in the Firefox browser only.

internalError()

It is supported in the Firefox browser only.

toSource()

It is a Non Standard method of the Error object.