Exception Handling in JavaScript
try
: This is where you put code that might cause an error. If an error happens, the program stops running this block and moves to thecatch{}
block.catch
: This block contains code that runs only if an error happened in thetry{}
block. If thetry{}
block runs without any errors, thecatch{}
block is skipped.finally
: This block contains code that will run no matter what – whether an error happened or not.throw
: This is used when you want to create your own errors.
function divide(num, den) {
try {
if (den === 0) {
throw new Error("Division by zero error");
}
console.log("Result of division:", num / den);
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("End of division operation");
}
}
try {
let numerator = 5;
let denominator = 0;
if (!isNaN(numerator) && !isNaN(denominator)) {
divide(numerator, denominator);
} else {
throw new Error("Invalid input, please enter integers.");
}
} catch (error) {
console.log("Error:", error.message);
}
Output
Error: Division by zero error End of division operation
Exception Handling in Programming
Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we’ll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
Table of Content
- What is Exception Handling?
- Components of Exception Handling
- Exception Handling in C
- Exception Handling in C++
- Exception Handling in Java
- Exception Handling in Python
- Exception Handling in C#
- Exception Handling in JavaScript
- Exception Handling Best Practices