Error handling

When executing JavaScript code, there are some cases where errors occur. There are two types of errors: 1. One is that the logic of the program is not correct, resulting in abnormal code execution. For example, var s = null; var len = s.length; // TypeError: Null variable has no length attribute for this type of error, fix the program. 2. The other is that during execution, the program may encounter unexpected exceptions and report errors, for example, network connection is interrupted, non-existent files are read, and there is no operation permission. For this kind of error, we need to deal with it and maybe give feedback to the user.

Error handling is a problem that must be considered in programming. For a language as close to the system as C, the error is returned by an error code:

int fd = open("/path/to/file", O_RDONLY);Copy the code

if (fd == -1) {Copy the code

    printf("Error when open file!");Copy the code

} else {Copy the code

    // TODOCopy the code

}Copy the code

To return an error with an error code, you need to agree on what is the correct return value and what is the wrong return value. The open() convention above returns -1 for an error. Obviously, this use of error codes to indicate errors is inconvenient when writing programs. As a result, high-level languages often provide more abstract error-handling logic such as try… catch … Finally, JavaScript is no exception.

try … catch … finally

Using a try… catch … When finally handles errors, we write the following code:

let r1,r2,s = null;Copy the code

try{Copy the code

r1 = s.length; // An error is reported hereCopy the code

    r2 = 100;Copy the code

} catch {Copy the code

    console.log('wrong' + e)Copy the code

} finally {Copy the code

    cosole.log('finally')Copy the code

}Copy the code

console.log('r1 = ' + r1 )      // r1 is undefinedCopy the code

console.log('r2 = ' + r2 )      // r2 is undefinedCopy the code

TypeError: Cannot read property ‘length’ of NULL Let’s analyze using try… catch … Finally execution flow. When the block is tried {… }, indicating that an error may occur during the execution of this part of the code. Once an error occurs, the subsequent code will not continue to execute and jump to the catch block. catch (e) { … } the wrapped code is the error handling code, and the variable e represents the captured error. Finally, with or without errors, finally must be executed.

Execute the process

So, when an error occurs, the execution flow looks like this: Try {… } code; When an error statement is reached, the subsequent statement is no longer executed and the catch (e) {… } code; Finally {… } code. When no errors occur, the execution flow looks like this: Try {… } code; Because there is no error, catch (e) {… } code will not be executed; Finally {… } code. Finally, notice that both catch and finally do not have to occur. That is, there are three forms of a try statement:

Complete try... catch ... Finally:Copy the code

try {Copy the code

.Copy the code

} catch (e) {Copy the code

.Copy the code

} finally {Copy the code

.Copy the code

}Copy the code

Only try... Catch, not finally:Copy the code

try {Copy the code

.Copy the code

} catch (e) {Copy the code

.Copy the code

}Copy the code

Only try... Finally, without catch:Copy the code

try {Copy the code

.Copy the code

} finally {Copy the code

.Copy the code

}Copy the code

Wrong type

JavaScript has a standard Error object for errors, as well as TypeError, ReferenceError, and other Error objects derived from Error. When we handle an error, we can access the error object through the variable e caught by catch(e) :

try {Copy the code

.Copy the code

} catch (e) {Copy the code

    if (e instanceof TypeError) {Copy the code

        alert('Type error! ');Copy the code

    } else if (e instanceof Error) {Copy the code

        alert(e.message);Copy the code

    } else {Copy the code

        alert('Error: ' + e);Copy the code

    }Copy the code

}Copy the code

It is customary to use the variable e, which can also be named after other variable names, such as Catch (ex).

Throw an error

A program can also actively throw an error that causes the execution flow to jump directly to the catch block. Throw error using throw statement.

throw new Error('This is a mistake')Copy the code

For example, when the front end asks the user to enter a number, the program receives what is actually a string, which is then converted to an integer with parseInt(). When user input is illegal, we throw an error;

In fact, JavaScript allows you to throw arbitrary objects, including numbers and strings. However, it is best to throw an Error object. Finally, when we catch an error, be sure to write an error handling statement:

var n = 0, s;Copy the code

try {Copy the code

    n = s.length;Copy the code

} catch (e) {Copy the code

    console.log(e);Copy the code

}Copy the code

console.log(n);Copy the code

Don't do nothing, even if it's just to print out the mistakes:Copy the code

var n = 0, s;Copy the code

try {Copy the code

    n = s.length;Copy the code

} catch (e) {Copy the code

}Copy the code

console.log(n);Copy the code

Since nothing is executed after catching an error, it is not known whether an error has occurred during the execution of the program. When handling errors, do not simply use alert() to display errors to the user. The tutorial code uses alert() for demonstration purposes

Error propagation

Source: public number — front end big bull lover

If an error occurs and the code is not tried… Where does the program execution flow jump to?

function getLength(s) {Copy the code

    return s.length;Copy the code

}Copy the code

Copy the code

function printLength() {Copy the code

    console.log(getLength('abc')); / / 3Copy the code

    console.log(getLength(null)); // Error!Copy the code

}Copy the code

Copy the code

printLength();Copy the code

Errors are also bubble propagated. If an error occurs inside a function and is not caught by itself, the error is thrown to the outer calling function. If the outer function is not caught, the error is thrown up the function call chain until it is caught by the JavaScript engine and the code terminates. So we don’t need to catch errors inside every function, just catch them all in one place:

When the bar() function passes null, an error is reported, and the error is thrown up to the caller foo(), which does not have a try… The catch statement, so the error continues to be thrown up to the caller main(), which has a try… Catch statement, so the error is eventually handled in the main() function. As to where it is appropriate to catch errors, it depends.

Asynchronous error handling

From teacher Liao Xuefeng’s blog

When writing JavaScript code, it is important to keep in mind that the JavaScript engine is an event-driven execution engine. The code is always executed in a single thread, and the callback function is not executed until the next event that meets the condition. For example, the setTimeout() function can pass in a callback and execute after a specified number of milliseconds:

function printTime() {Copy the code

    console.log('It is time! ');Copy the code

}Copy the code

Copy the code

setTimeout(printTime, 1000);Copy the code

console.log('done');Copy the code

The code above will print done first and will print It is time 1 second later. . If there is an error inside printTime(), our attempt to wrap setTimeout() with a try is invalid:

Asynchronous errors can only be caught and handled within asynchronous functions

The reason is that when setTimeout() is called, the printTime function passed in is not executed immediately! Next, the JavaScript engine continues to execute console.log(‘done’); Statement, while no error has occurred. An error does not occur until one second later when the printTime function is executed, but the outer code does not catch the error except inside the printTime function. So, when it comes to asynchronous code, it cannot be captured at call time because the callback function is not executed at the time it is captured. Similarly, when we process an event, we cannot catch the error of the event handler in the code that binds the event. For example, for the following form:

<form>Copy the code

    <input id="x"> + <input id="y">Copy the code

    <button id="calc" type="button"> computing < / button >Copy the code

</form>Copy the code

Copy the code



We bind the click event to button with the following code:

try{Copy the code

    $btn.click(function() {Copy the code

        var x = parseFloat($('#x').val()),Copy the code

        var y = parseFloat($('#y').val()),Copy the code

            r;Copy the code

        if(isNaN(x) || isNaN(y)){Copy the code

            throw new Error('Input error');Copy the code

        }Copy the code

        r = x + y;Copy the code

        alert('Calculation result:' + r);Copy the code

    })Copy the code

} catch(e) {Copy the code

    alert('Input error')Copy the code

}Copy the code

However, when the user typed an error, the handler did not catch the error. Fix the error handling code.

(1) mp.weixin.qq.com/s?__biz=MzU… (2) mp.weixin.qq.com/s?__biz=MzU… (3) mp.weixin.qq.com/s/oJJNxgG95…