Try-Catch-Finally in JavaScript
Basic error handling with try-catch-finally
BeginnerError HandlingExample 1 of 10
try-catch-finally.js
1// Method 1: Basic try-catch2try {3 const result = 10 / 0;4 console.log('Result:', result);5} catch (error) {6 console.error('Error occurred:', error.message);7}89// Method 2: Try-catch with specific error10try {11 const data = JSON.parse('invalid json');12} catch (error) {13 if (error instanceof SyntaxError) {14 console.error('JSON parse error:', error.message);15 } else {16 console.error('Unknown error:', error);17 }18}1920// Method 3: Try-catch-finally21try {22 console.log('Trying...');23 throw new Error('Something went wrong');24} catch (error) {25 console.error('Caught error:', error.message);26} finally {27 console.log('Finally block always executes');28}2930// Method 4: Nested try-catch31try {32 try {33 throw new Error('Inner error');34 } catch (innerError) {35 console.error('Inner catch:', innerError.message);36 throw new Error('Outer error');37 }38} catch (outerError) {39 console.error('Outer catch:', outerError.message);40}4142// Method 5: Error object properties43try {44 throw new Error('Test error');45} catch (error) {46 console.log('Error name:', error.name);47 console.log('Error message:', error.message);48 console.log('Error stack:', error.stack);49}5051// Method 6: Custom error handling52function riskyOperation() {53 if (Math.random() > 0.5) {54 throw new Error('Random error');55 }56 return 'Success';57}5859try {60 const result = riskyOperation();61 console.log('Result:', result);62} catch (error) {63 console.error('Operation failed:', error.message);64}6566// Method 7: Multiple catch blocks (not supported, use if-else)67try {68 throw new TypeError('Type error');69} catch (error) {70 if (error instanceof TypeError) {71 console.error('Type error:', error.message);72 } else if (error instanceof ReferenceError) {73 console.error('Reference error:', error.message);74 } else {75 console.error('Other error:', error.message);76 }77}7879// Method 8: Error in async function80async function asyncOperation() {81 try {82 const response = await fetch('https://api.example.com/data');83 const data = await response.json();84 return data;85 } catch (error) {86 console.error('Async error:', error.message);87 throw error; // Re-throw if needed88 }89}9091asyncOperation().catch(error => {92 console.error('Unhandled async error:', error);93});
Output
Result: Infinity
JSON parse error: Unexpected token i in JSON at position 0
Trying...
Caught error: Something went wrong
Finally block always executes
Inner catch: Inner error
Outer catch: Outer error
Error name: Error
Error message: Test error
Error stack: Error: Test error
at ...
Operation failed: Random error
Type error: Type error
Async error: Failed to fetchWhat's going on
Try-catch-finally handles errors.
Try Block
Code that might throw
Execute normally if no error
Stop on error
Catch Block
Handle errors
Access error object
Prevent crash
Finally Block
Always executes
Cleanup code
Even if error thrown
Error Object
name: Error type
message: Error message
stack: Stack trace
Error Types
Error: Generic
TypeError: Type mismatch
ReferenceError: Undefined variable
SyntaxError: Parse error
Best Practices
Catch specific errors
Log errors properly
Use finally for cleanup
Re-throw if needed