Error Handling & Debugging
try, catch, and finally
The `try...catch` statement lets you handle runtime errors gracefully, preventing the program from crashing.
- `try` contains the code that might throw an error.
- `catch` runs if an error occurs inside `try`.
- `finally` always executes, whether an error occurred or not.
try {
let result = 10 / 0; // No error, but result is Infinity
console.log(result);
} catch (error) {
console.log("Something went wrong:", error.message);
} finally {
console.log("This always runs");
}
// Output:
// Infinity
// This always runs