Posts

Showing posts from July, 2023

What are Caught and Uncaught Exceptions in JavaScript?

In JavaScript, there are two types of exceptions: Caught exceptions: These are exceptions that are handled by a try/catch block. For example: try { // Code that may cause an exception throw new Error("Something went wrong!"); } catch (err) { // This will catch the exception and handle it console.log(err.message); // Prints "Something went wrong!" } Here the exception is caught and handled. Uncaught exceptions: These are exceptions that are thrown but not caught by a try/catch block. For example: throw new Error("Something went wrong!"); Here the exception is thrown but not caught, so it bubbles up and causes the JS execution to stop. These can crash your program if unhandled. It's good practice to use try/catch blocks to catch exceptions you expect, and have a general catch block at a high level to catch any uncaught exceptions and handle them gracefully. For example: try { // Code that may cause exceptions } catch (err)