What is the role of throw statement in JavaScript?

The throw statement in JavaScript is used to manually create and raise exceptions. When executed, it stops the normal execution flow and passes control to the nearest catch block.

Syntax

throw expression;

The expression can be any value: string, number, boolean, object, or Error instance.

Basic Example

Here's how to use throw with a simple string message:

<html>
<head>
    <script>
        function checkDivision() {
            var a = 100;
            var b = 0;
            try {
                if (b == 0) {
                    throw "Divide by zero error.";
                } else {
                    var c = a / b;
                    alert("Result: " + c);
                }
            } catch (e) {
                alert("Error: " + e);
            }
        }
    </script>
</head>
<body>
    <p>Click the button to test division by zero:</p>
    <button onclick="checkDivision()">Test Division</button>
</body>
</html>

Throwing Different Types

You can throw various data types as exceptions:

<html>
<head>
    <script>
        function demonstrateThrow() {
            try {
                // Throwing a string
                throw "This is a string error";
            } catch (e) {
                console.log("Caught:", e);
            }

            try {
                // Throwing a number
                throw 404;
            } catch (e) {
                console.log("Error code:", e);
            }

            try {
                // Throwing an Error object
                throw new Error("This is an Error object");
            } catch (e) {
                console.log("Error name:", e.name);
                console.log("Error message:", e.message);
            }
        }
        
        demonstrateThrow();
    </script>
</head>
<body>
    <p>Check the browser console for output.</p>
</body>
</html>

Custom Error Classes

For better error handling, create custom error types:

<html>
<head>
    <script>
        class ValidationError extends Error {
            constructor(message) {
                super(message);
                this.name = "ValidationError";
            }
        }

        function validateAge(age) {
            try {
                if (age < 0) {
                    throw new ValidationError("Age cannot be negative");
                }
                if (age > 150) {
                    throw new ValidationError("Age seems unrealistic");
                }
                alert("Valid age: " + age);
            } catch (e) {
                if (e instanceof ValidationError) {
                    alert("Validation Error: " + e.message);
                } else {
                    alert("Unexpected error: " + e.message);
                }
            }
        }
    </script>
</head>
<body>
    <p>Test age validation:</p>
    <button onclick="validateAge(-5)">Test Negative Age</button>
    <button onclick="validateAge(200)">Test High Age</button>
    <button onclick="validateAge(25)">Test Valid Age</button>
</body>
</html>

Key Points

  • throw immediately stops execution and jumps to the nearest catch block
  • If no catch block exists, the error becomes an unhandled exception
  • Best practice is to throw Error objects rather than primitive values
  • Custom error classes provide better error categorization and handling

Conclusion

The throw statement is essential for creating robust error handling in JavaScript. Use it to validate inputs, handle exceptional conditions, and create meaningful error messages for better debugging.

Updated on: 2026-03-15T23:18:59+05:30

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements