JavaScript (vi): error handling mechanism

Source: Internet
Author: User
Tags eval

1.Error () constructor

When JavaScript parses or executes a statement, the JS engine throws it whenever an error occurs!

JavaScript primitives provide the error () constructor , and all thrown errors are instances of this constructor (that is, objects ).

1 var err1=New error (' shows error '); 2 Console.log (ERR1); 3 Console.log (err1.message);

Operation Result:

ERR1 is an instance object produced by the error () constructor, and the object has the message property provided by all JavaScript engines!

When the code runs or resolves an error, the JS engine throws an error, and the program breaks where the error occurs and no longer executes!

Some JS engines also provide the name and stack properties of the wrong object. But remember that they are not standard, not necessarily every JS engine is provided!

    • Message: Error message
    • Name: Error name (non-standard attribute)
    • Stack: Bad stacks (non-standard properties)
1 var err2=New error (' This is Error 2 '); 2 Console.log (err2.message); // This is error 2 3 Console.log (err2.name); // Error 4 Console.log (err2.stack); // Error:this is the Error 2 at   7.js:5

Operation Result:

2.javascript native Error constructor

In addition to error (), JS also defines 6 more detailed constructors :

    1. SyntaxError (): Syntax error
    2. Referenceerror (): Reference error
    3. Rangeerror (): Error exceeding valid range
    4. TypeError (): Type error
    5. Urierror (): URI error
    6. Evalerror (): The eval function was not executed correctly. Note: This constructor no longer appears in ES5 , and now some places remain, just for compatibility!
1 varerr3=NewError (' ERROR ');2 varerr4=NewSyntaxError (' syntax error '));3 varerr5=NewReferenceerror (' reference error '));4 varerr6=NewRangeerror (' range exceeded error '));5 varerr7=NewTypeError (' type error '));6 varerr8=NewUrierror (' URI error '));7 varerr9=NewEvalerror (' eval function use error ');8 Console.log (ERR3,ERR4,ERR5,ERR6,ERR7,ERR8,ERR9);9Console.log (typeofError,typeofSyntaxError);//function Function

Operation Result:

3. Custom Error objects (except 7 constructors built in JavaScript create Error objects)

1 functionErrora (message) {2      This. message= message | | Error;3      This. Name= ' Errora ';4 }5 //make Errora inherit error6Errora.prototype=NewError ();7Errora.prototype.constructor=Errora;8 9 varerr10=NewErrora (' Generated Errora Error object ');TenConsole.log (ERR10);

Operation Result:

4.throw Statement : Receives an expression as a parameter, throws an error or unexpected, interrupts the execution of the program!

Common uses such as: throw new error (' Error here ');

1 var a=100; 2 Console.log (a); 3 Throw New Error (' error shows '); // The program is interrupted here and will not be executed down 4 console.log (1000); // The program does not execute here

Operation Result:

Simulate the Assert method of the console object: If the passed-in parameter is not the correct expression, an error is thrown .

 1  console.log ('---'  2  function   ASSERT (Expression,message) { 3  if  ( ! expression) { 4  throw  {name: ' Assert function ' ,meaage:message};  5  }  6  }  7  assert (' Error shows 1 '); Span style= "COLOR: #008000" >//  No error at this time  8  assert (Undefined, ' Error shows 2 '); //  

Operation Result:

Using Console.assert ():

5.try...catch statement: Handle the error, the structure has a try, the general will have catch. Finnally don't have to!

When an error is thrown in a try, the program immediately jumps to the catch to execute.

Here's an example: try throws multiple errors, but only the first error is captured!

1Console.log ('---');2 Try{3     Throw NewTypeError (' type error ');//jump to catch for capture4     Throw NewRangeerror (' range exceeded error ');//does not execute5}Catch(e) {6 Console.log (e); 7}finally{8Console.log (' finnally ');9}

Operation Result:

Optionally, you can nest statements in catch (for example: Try...catch)

1Console.log ('---');2 Try{3     Throw NewTypeError (' type error ');//jump to catch for capture4     Throw NewRangeerror (' range exceeded error ');//does not execute5}Catch(e) {6     if(Einstanceofrangeerror) {7 Console.log (e);8}Else{9         //nested the Try...catch statementTen         Try{ One             Throwe; A}Catch(e) { -             if(EinstanceofTypeError) { -Console.log (' nesting '); the Console.log (e.message); -}Else{ -                 ThrowE//If you do not meet the criteria, continue to throw, you can continue to nest -             } +         } -     } +             A}finally{ atConsole.log (' finnally '); -}

Operation Result:

Note: The Try...catch statement is poorly handled and prone to the destruction of structured programming principles . Use caution !!!

If there is a return in the catch, pay attention to the execution result:

1Console.log ('---');2 vara=10;3 functionTest () {4     Try{5         ThrowA;6         returnA + ' 1 ';//+ ' 1 ' to identify where the value returned from7}Catch(e) {8         returnA//The return value has been saved before finally execution, and the saved value is returned immediately after execution of Finnally9}finally{Tena+=10; One     } A } -Console.log (Test ());//Ten -Console.log (a);// -

Operation Result:

Reference: Nanyi JavaScript standard reference Tutorial

JavaScript (vi): error handling mechanism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.