Home  >  Article  >  Web Front-end  >  JS exception capture try-catch statement method example

JS exception capture try-catch statement method example

小云云
小云云Original
2018-03-08 16:12:401822browse

The third edition of ECMA-262 introduced the try-catch statement as the standard way to handle exceptions in JS. The basic syntax is as follows

try{
    //可能导致错误的代码
} catch(eroor){
    //在错误发生时的处理方式
}

That is, all code that may throw errors must be placed in the try statement block. If an exception occurs, the catch statement block will receive an object containing error information, even if There is no need to use this object, you must also declare it, like error in the above code.

1. finally clause

In addition to the basic try-catch statement, there is also a finally clause. If a finally clause is added, No matter whether an exception error occurs or not, no matter what code is used (even if a return statement is used), it will not affect the execution of the finally clause. This is very important. a little.

function testFinally(){
    try{
        return 2;
    } catch(error){
        return 1;
    } finnaly{
        return 0;
    }
}

When executing the above function, it will not return 2 or 1, but will always return 0.

If a finally clause is provided, the catch clause becomes optional (one of catch or finally is enough), but In IE7 or earlier versions, if there is no catch clause, the code in finally will not be executed.

2. Error types

ECMA-262 defines the following 7 error types: Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError.

Where Error is the base type from which other error types inherit, so all error types share the same set of properties. Error type errors are rare and generally used for developer-defined errors.

Related recommendations:

PHP Try-catch statement usage skills_php skills

The above is the detailed content of JS exception capture try-catch statement method example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn