Site icon i2tutorials

Javascript-Try Catch

Javascript-Try Catch

 

A try…catch statement is a commonly used statement in different programming languages. Basically, the try…catch statement is used to handle the error part of the code. It is initially testing the code for all possible errors it may contain, then it implements actions to tackle those errors.

 

Syntax:

 

try {
 try_statements
}
[catch [(exception_var)] {
 catch_statements
}]
[finally {
 finally_statements
}]

 

 

Each block of statement individually:

 

 

try{} statement: The code which needs possible error testing is kept within the try block. In case any error occurs, it passes to the catch{} block for taking suitable actions and handle the error. Otherwise, it executes the code written within.

 

catch{} statement: This block handles the error of the code by executing the set of statements written within the block of code. This block provides either the user-defined exception handler or the built-in handler. This block of code executes only when any error-prone code needs to be handled in the try block. Otherwise, the catch block is skipped.

 

Finally-block: It is will always execute after the try-block and catch-block(s) have finished executing. this is always executed and regardless of whether an exception was thrown or caught.

 

Example:

 

<html>
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a);    // displays elements of a
document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be invoked
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script>
</body>
</html>

 

OUTPUT:

 

Exception Handling

34,32,5,31,24,44,67

 

Throw Statement:

 

These statements are used for throwing user-defined errors.Users can define and throw their own custom errors.

 

Syntax:

 

throw exception;

 

try…catch…throw syntax:

 

try{ 
throw exception; // user can define their own exception 
} 
catch(error){ 
expression; }  // code for handling exception.

 

Example:

 

<html>
<head>Exception Handling</head>
<body>
<script>
try {
  throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e) {
 document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>

 

OUTPUT:

 

Exception Handling This is the throw keyword

 

try…catch…finally statements:

 

Syntax:

 

try{ 
expression; 
} 
catch(error){ 
expression; 
} 
finally{ 
expression; } //Executable code

 

example:

 

<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>

 

OUTPUT:

 

Exception Handling okValue of a is 2

 

 

Exit mobile version