Home > Web Front-end > JS Tutorial > body text

JS exception capture try-catch statement method example

小云云
Release: 2018-03-08 16:12:40
Original
1886 people have browsed it

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){
    //在错误发生时的处理方式
}
Copy after login

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;
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!