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

Try catch usage in javascript_javascript skills

WBOY
Release: 2016-05-16 15:44:45
Original
1334 people have browsed it

Let’s look at an example first

<input id='b1' type='button' value='按钮'/>
<script>
window.onload=function(){
var oBtn=document.getElementById("b1");
function mto(){
alert("123");
};

try //非IE
{
oBtn.attachEvent("onclick",mto,false);

}
catch(e)//IE
{
oBtn.addEventListener("click",mto,false);
}
};
</script>

Copy after login

Note:

The difference between addEventListener and attachEvent is the first parameter. The former is click and the latter is onclick

addEventListener runs in the element scope of its element

attachEvent runs in the global scope (this=window)

Try...Catch statement

try...catch can test for errors in your code. The try section contains the code that needs to be run, while the catch section contains the code that runs when an error occurs.
Syntax:

try
{
//在此运行代码
}
catch(err)
{
//在此处理错误
}

Copy after login

Note: use lowercase letters for try...catch. Capital letters will go wrong.

try...catch...finally statement

Implement error handling for JScript . 

  try  {  
     tryStatements}  
  catch(exception){  
     catchStatements}  
  finally  {  
     finallyStatements}  
Copy after login

============== ===========       

Parameters

tryStatement

Required option. An incorrect statement may occur.     
exception
Required option. any variable name. The initialization value of exception is the value of the error thrown.     
catchStatement
Optional. Statement that handles errors that occur in the associated tryStatement .     
finallyStatements
Optional. A statement that is executed unconditionally after all other processes have occurred.       

Description

The try...catch...finally statement provides a way to handle some or all errors that may occur in a given block of code while still keeping the code running. If an error occurs that is not handled by the programmer, JScript only provides its normal error message to the user, as if there was no error handling. 


The

tryStatements parameter contains code for possible errors, while catchStatement contains code for handling any errors that occur. If an error occurs in tryStatements , program control is passed to catchStatements for processing. The initialization value of exception is the value of the error that occurred in tryStatements . If an error does not occur, catchStatements are not executed. 


If the error cannot be handled in the catchStatements associated with the tryStatements where the error occurred, use a throw statement to propagate or re-throw the error to a higher-level error handler. 


After the statements in tryStatements are executed and all error handling in catchStatements occurs, the statements in finallyStatements can be executed unconditionally. 


Please note that even if a statement is returned in a try or catch block, or an error is re-thrown in a catch block, the finallyStatements encoding will still be executed. Will generally ensure that finallyStatments runs unless there are unhandled errors. (For example, a runtime error occurs in a catch block.).

Example


The following example illustrates how JScript special case handling is performed. 


  try  {  
    print("Outer  try  running..");  
    try  {  
      print("Nested  try  running...");  
      throw  "an  error";  
    }  
    catch(e)  {  
      print("Nested  catch  caught  "  +  e);  
      throw  e  +  "  re-thrown";  
    }  
    finally  {  
      print("Nested  finally  is  running...");  
    }     
  }  
  catch(e)  {  
    print("Outer  catch  caught  "  +  e);  
  }  
  finally  {  
    print("Outer  finally  running");  
  }  
  //  Windows  Script  Host  作出该修改从而得出  WScript.Echo(s)  
  function  print(s){  
     document.write(s);  
  }  
Copy after login
will produce the following results:


Outer try running..

Nested try running...
Nested catch caught caught an error
Nested finally is running...
Outer catch caught caught an error re-thrown
Outer finally running

The following is an example of Javascript exception handling.

var array = null;
try {
  document.write(array[0]);
} catch(err) {
  document.writeln("Error name: " + err.name + "");
  document.writeln("Error message: " + err.message);
}
finally{
  alert("object is null");
}

Copy after login

Program execution process

1. Since the array array is not created when array[0] is used, array is an empty object. Calling array[0] in the program will generate an object is null exception
2. The catch(err) statement captures this exception and prints the error type through err.name, and err.message prints the error details.
3. finally is similar to java's finally, it will be executed regardless of whether there is an exception or not.

Now summarize the information corresponding to the six values ​​​​of Error.name:

1. EvalError: The use of eval() is inconsistent with the definition
2. RangeError: Value out of bounds
3. ReferenceError: Illegal or unrecognized reference value
4. SyntaxError: A syntax parsing error occurred
5. TypeError: Wrong operand type
6. URIError: Improper use of URI processing function

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