98. Error Handling with try...catch (Synchronous)
try...catch is the standard block structure used to handle errors in synchronous JavaScript code.
How It Works
tryblock: Contains the code that might potentially throw an error.catchblock: If an error occurs within thetryblock, execution immediately jumps here. It receives the error object as an argument.
Syntax
javascript try { // Code that is monitored for errors let result = riskyFunction(); console.log(result); } catch (error) { // Code that executes if an error is thrown in the try block console.error('An error was caught:', error.message); }
console.log('Execution continues outside the block.');
Throwing Custom Errors
You can manually stop execution and signal an error using the throw statement.
javascript function divide(a, b) { if (b === 0) { throw new Error('Division by zero is not allowed.'); } return a / b; }
try { console.log(divide(10, 0)); } catch (e) { console.error(e.message); // Division by zero is not allowed. }