Logo
HTMLCSSJavaScriptReactjsnewContactUpdates

Get started today

HTMLCSSJavaScriptReactjsnewContactUpdates

Tools

Resume BuilderQR GeneratorVS Code Editor

Connect

GitHubWhatsApp Channel
event
asynchronous javascript

Javascript Exception Handling

By Saket Bhatnagar•June 15, 2025•Beginner to Intermediate

Table of Contents

  1. Exception
  2. Exception handling
  3. try , catch and finally
  4. throw

Exception

  1. 1Exception is an unwanted or unexpected problem, which occurs during the execution of a program.
  2. 2If unexpected problem occurs at runtime , program execution will be disrupted.
  3. 3Example: file input/output errors, or network communication errors.

Exception handling

  1. 1The process of handling unwanted or unexpected problem at runtime without affecting program execution is called as

    Exception handling

    .
  2. 2We can handle these exceptions using try, catch and finally.

try , catch and finally

  1. try

    • 1The try block contains the code that might throw an exception.
    • 2If an exception occurs within the try block, control is immediately transferred to the corresponding catch block.
  2. catch

    • 1The catch block is used to handle exceptions that are thrown within the corresponding try block.
    • 2It contains code that will be executed if an exception is thrown, and is typically used to handle the exception in some way (e.g., logging an error message, displaying a user-friendly error message, or taking some other appropriate action).
  3. finally

    • 1The finally block is used to specify code that should be executed regardless of whether or not an exception is thrown.
    • 2This block is typically used to clean up resources (e.g., closing files or closing network connections) that were allocated within the try block.
  4. Example

    • 1
      1try {
      2 // Code that might throw an exception
      3
      4 const num = Number(prompt("Enter a number"));
      5 if (isNaN(num)) {
      6 throw new Error("Invalid number");
      7 }
      8 console.log("You entered the number " + num);
      9} catch (err) {
      10 // Code to handle the exception
      11
      12 console.error("An error occurred: "+err.message);
      13} finally {
      14 // Code to be executed regardless of whether an exception was thrown or not
      15
      16 console.log("Execution complete");
      17}

throw

  1. 1throw is a keyword used to manually trigger an exception.
  2. 2When throw is used, it causes the JavaScript interpreter to stop executing the current block of code and transfer control to the nearest catch block that can handle the exception.

Share this article

Last updated: July 15, 2025

Join Our Community

Login to Join

© 2025 Saket Bhatnagar. All rights reserved.

    ☕