1. Exception is an unwanted or unexpected problem, which occurs during the execution of a program.
2. If unexpected problem occurs at runtime, program execution will be disrupted.
3. Example: file input/output errors, or network communication errors.
Exception handling
1. The process of handling unwanted or unexpected problem at runtime without affecting program execution is called as Exception handling.
2. We can handle these exceptions using try, catch and finally.
try, catch and finally
1. try
1. The try block contains the code that might throw an exception.
2. If an exception occurs within the try block, control is immediately transferred to the corresponding catch block.
2. catch
1. The catch block is used to handle exceptions that are thrown within the corresponding try block.
2. It 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
1. The finally block is used to specify code that should be executed regardless of whether or not an exception is thrown.
2. This 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.
try {
// Code that might throw an exception
const num = Number(prompt("Enter a number"));
if (isNaN(num)) {
throw new Error("Invalid number");
}
console.log("You entered the number " + num);
} catch (err) {
// Code to handle the exception
console.error("An error occurred: "+err.message);
} finally {
// Code to be executed regardless of whether an exception was thrown or not
console.log("Execution complete");
}
Throw
1. Throw is a keyword used to manually trigger an exception.
2. When 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.