Blog JavaScript Programming

JavaScript is a loosely-typed language. It does not give compile-time errors. So some times you will get a runtime error for accessing an undefined variable or calling undefined function etc.

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#.

Syntax:
try
{
    // code that may throw an error
}
catch(ex)
{
    // code to be executed if an error occurs
}
finally{
    // code to be executed regardless of an error occurs or not
}
  • try: wrap suspicious code that may throw an error in the try block.
  • catch: write code to do something in the catch block when an error occurs. The catch block can have parameters that will give you error information. Generally, a catch block is used to log an error or display specific messages to the user.
  • finally: code in the finally block will always be executed regardless of the occurrence of an error. The finally block can be used to complete the remaining task or reset variables that might have changed before error occurred in the try block.

Let’s look at simple error handling examples.

Example: Error Handling in JS

try { 
var result = Sum(10, 20); // Sum is not defined yet 
} catch(ex) { 
document.getElementById("errorMessage").innerHTML = ex; 
}

In the above example, we are calling the function Sum, which is not defined yet. So, try block will throw an error which will be handled by the catch block. Ex includes error messages that can be displayed.

The finally block executes regardless of whatever happens.

Example: finally Block

try
{
     var result  =  Sum(10, 20); // Sum is not defined yet
}catch(ex){
    document.getElementById("errorMessage").innerHTML = ex;
}finally{
    document.getElementById("message").innerHTML = "finally block executed";
}

4.1 Throw

Use throw keyword to raise a custom error.

Example: throw error with error info

try 
{
    throw {
        number: 101,
        message: "Error occurred"
    };
}catch (ex) {
    alert(ex.number + "- " + ex.message);
}

predragacademy

Leave a Reply