Wednesday, 19 February 2025

Exception handling in JavaScript

 

Exception handling is a programming concept that helps developers manage errors and unexpected events in a structured and controlled way. In JavaScript, this is done using the try...catch statement, which allows you to handle exceptions (errors) gracefully rather than having the program crash.

 

What is an Exception?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. It can be caused by various reasons, such as

 

1.   Syntax errors: Mistakes in the syntax of the code, like missing a closing parenthesis.

2.   Runtime errors: Errors that occur while the program is running, like trying to access a variable that doesn't exist or attempting to divide by zero.

3.   Logical errors: Errors in the logic of the code that produce unintended behaviour.

 

How to handle exceptions in JavaScript?

JavaScript provides the try...catch...finally construct for exception handling.

 

1.   try Block: Code that might throw an exception is placed inside the try block. If an exception occurs, the execution of the code inside the try block stops immediately, and control is transferred to the catch block.

 

2.   catch Block: This block catches the exception thrown from the try block. It allows you to define a block of code that will be executed if an exception occurs. The catch block can also access the exception object, which provides details about the error.

 

3.   finally Block (Optional): This block contains code that will run regardless of whether an exception was thrown or not. It's typically used for cleanup tasks, such as closing files, releasing resources, or resetting variables.

 

Syntax 

try {
    // Code that may throw an exception
} catch (error) {
    // Code to handle the exception
} finally {
    // Code that will run regardless of the exception
}

hello-world.js

function divideNumbers(a, b) {
    try {
        if (typeof a !== 'number' || typeof b !== 'number') {
            throw new Error('Both arguments must be numbers');
        }

        if (b === 0) {
            throw new Error('Division by zero is not allowed');
        }

        let result = a / b;
        console.log(`Result: ${result}`);
    } catch (error) {
        console.log(`An error occurred: ${error.message}`);
    } finally {
        console.log('Execution completed.');
    }
}

// Test cases
divideNumbers(10, 2);   // Should print: Result: 5, Execution completed.
divideNumbers(10, 0);   // Should print: An error occurred: Division by zero is not allowed, Execution completed.
divideNumbers(10, 'a'); // Should print: An error occurred: Both arguments must be numbers, Execution completed.

Output

Result: 5
Execution completed.
An error occurred: Division by zero is not allowed
Execution completed.
An error occurred: Both arguments must be numbers
Execution completed.

 

Built-in Error Types in JavaScript

JavaScript has several built-in error types, each of which serves a different purpose:

 

1.   Error: A generic error.

2.   SyntaxError: Thrown when the syntax is incorrect (e.g., eval('var a = ;')).

3.   ReferenceError: Thrown when an invalid reference is used (e.g., accessing an undeclared variable).

4.   TypeError: Thrown when a value is not of the expected type (e.g., calling a non-function as a function).

5.   RangeError: Thrown when a numeric value is out of range (e.g., passing a negative number to Array.prototype.repeat()).

6.   URIError: Thrown when there's an error in encoding or decoding a URI.

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment