Exception Handling Statements

Source: Internet
Author: User
Tags finally block month name

You can throw exceptions using the throw statement and handle them using the try...catch statements.

    • throwStatement
    • try...catchStatement
Exception types

Just about any object can is thrown in JavaScript. Nevertheless, not all thrown objects is created equal. While it's fairly common to throw numbers or strings as errors it's frequently more effective to use one of the exceptio n types specifically created for this purpose:

    • ECMAScript exceptions
    • DOMExceptionandDOMError
throwStatement

Use the throw statement to throw a exception. When you throw a exception, you specify the expression containing the value of be thrown:

throw expression;

  

You may throw an any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:

Throw "Error2";   String Typethrow;         Number Typethrow true;       Boolean Typethrow {tostring:function () {return "I ' m an object!";}};

  

Note:You can specify a object when you throw a exception. You can then reference the object's properties in the catchBlock. The following example creates an object myUserExceptionof type UserExceptionand uses it in a throw statement.
Create an Object type userexceptionfunction userexception (message) {  this.message=message;  This.name= "Userexception";} Make the exception convert to a pretty string when used as a string//(e.g. by the error console) Userexception.prototy pe.tostring = function () {  return this.name + ': "' + This.message + '";} Create an instance of the object type and a throw itthrow new Userexception ("Value too High");

  

try...catchStatement

try...catchThe statement marks a block of statements to try, and specifies one or more responses should an exception is thrown. If An exception is thrown, the try...catch statement catches it.

Thetry...catchStatement consists of atryblock, which contains one or more statements, and zero or morecatchBlocks, containing statements that specify "what" if a exception is thrown in thetryBlock. That's, you want thetryBlock to succeed, and if it does isn't succeed, you want control to pass to thecatchBlock. If any statement within thetryBlock (or in a function called from within thetryBlock) throws an exception, control immediately shifts to thecatchBlock. If no exception is thrown in thetryBlock, thecatchBlock is skipped. ThefinallyBlock executes after thetryandcatchBlocks execute but before the statements following thetry...catchStatement.

The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1-12), an exception are thrown with the value and the "InvalidMonthNo" statements In the catch block set, the monthName variable to unknown .

function Getmonthname (MO) {  mo = mo-1;//Adjust month number for array index (1=jan, 12=dec)  var months = ["Jan" , "Feb", "Mar", "APR", "may", "June", "Jul", "April",                "Sep", "Oct", "Nov", "Dec"];  if (Months[mo]! = null) {    return months[mo];  } else {    throw "Invalidmonthno";//throw keyword is used here
   
    }}try {//statements to try  monthName = getmonthname (mymonth);//function could throw Exception}catch (e) {  Mon Thname = "Unknown";  
   

  

The catchBlock

You can use a catch block-to-handle all exceptions, which is generated in the try block.

catch (Catchid) {  statements}

  

The catch block specifies an identifier (in the catchID preceding syntax) that holds the value specified by the throw statem Ent You can use this identifier-get information about the exception, was thrown.  JavaScript creates this identifier when the catch block was entered; The identifier lasts only for the duration catch of the Block After catch The block finishes executing, the identifier is no longer available.

For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.

try {  throw "myexception"//Generates an Exception}catch (e) {  //statements to handle any exceptions  Logmyer Rors (e)//Pass exception object to error handler}

  

The finallyBlock

The finally block contains statements to execute after the try and catch blocks execute but before the statements Followin G The try...catch statement. The finally block executes whether or not a exception is thrown. If an exception are thrown, the statements in the finally block execute even if no catch block handles the exception.

You can use finally the block-to-make your script-fail gracefully when a exception occurs; For example, if you are need to rel Ease a resource that your script have tied up. The following example opens a file and then executes statements this use the file (Server-side JavaScript allows your to AC cess files). If an exception was thrown while the file is open, the finally block closes the file before the script fails.

Openmyfile (); try {  writemyfile (thedata);//this may throw a error} catch (e) {    handleError (e);//If we got a error We handle it} finally {  closemyfile ();//Always close the resource}

  

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally production, regardless of any c2/> statements in the try and catch blocks:

function f () {  try {    console.log (0);    Throw "bogus";  } catch (e) {    console.log (1);    return true; This return statement is suspended                 //until finally block have completed    Console.log (2);//Not reachable
   
    } finally {    console.log (3);    return false; Overwrites the previous "return"    Console.log (4);//Not reachable  }  //"return false" was executed now    
   

  

Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:

function f () {  try {    throw "bogus";  } catch (e) {    console.log (' caught inner "bogus");    Throw e; This throw statement was suspended until              //finally block has completed  } finally {    return false;//Overwri TES the previous "throw"  }  //"return false" is executed Now}try {  f ();} catch (e) {  //it is never r Eached because the throw inside  //The catch is overwritten  //By the return in the finally  

  

Nesting try...catch Statements

You can nest one or more try...catch statements. If an inner try...catch statement does not has a catch block, the enclosing try...catch statement ' s catch block is checked for a MATC H.

Utilizing ErrorObjects

Depending on the type of error, you may be able to use the ' name ' and ' message ' properties to get a more refined message. ' Name ' provides the general class of error (e.g., ' domexception ' or ' error '), while ' message ' generally provides a more Su CCINCT message than one would get by converting the Error object to a string.

If you is throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn ' t discriminate between your own exceptions and system ones), you can use the Error constructor. For example:

function Dosomethingerrorprone () {  if (Ourcodemakesamistake ()) {    throw (new Error (' the message '));  } else {    dosomethingtogetajavascripterror ();  }} ..... try {  dosomethingerrorprone ();} catch (e) {  console.log (e.name);//logs ' Error '  

  

Exception Handling Statements

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.