Module 6: Errors, Debugging, and Troubleshooting
Handling Errors: try, catch, finally, throw
JavaScript provides mechanisms to gracefully handle runtime errors (exceptions) and prevent your program from crashing.
1. try...catch
statement:
- The
try
block contains code that might throw an error. - If an error occurs within the
try
block, execution immediately jumps to thecatch
block. - The
catch
block receives an error object (often namede
orerror
) containing information about the error.
try { let result = some riskyOperation(); console.log(result); } catch (error) { console.error("An error occurred: " + error.message); // You can also log error.name or error.stack for more details } console.log("Execution continues after try...catch.");
2. try...catch...finally
statement:
- The
finally
block executes after thetry
andcatch
blocks, regardless of whether an error occurred or was caught. - It's often used for cleanup code (e.g., closing files, releasing resources).
try { console.log("Attempting operation..."); // potentiallyErrorProneCode(); console.log("Operation successful (or no error thrown)."); } catch (e) { console.error("Error caught: " + e.message); } finally { console.log("Finally block executed - cleanup tasks here."); }
3. throw
statement:
Allows you to create and throw your own custom errors or re-throw existing ones.
You can throw any expression, but it's common to throw Error
objects or instances of custom error classes derived from Error
.
function validateAge(age) { if (typeof age !== 'number') { throw new TypeError("Age must be a number."); } if (age < 0) { throw new RangeError("Age cannot be negative."); } console.log("Age is valid: " + age); } try { validateAge(25); validateAge(-5); } catch (e) { console.error(e.name + ": " + e.message); } // Output for validateAge(-5) -> RangeError: Age cannot be negative.