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-catch
2try {
3 const result = 10 / 0;
4 console.log('Result:', result);
5} catch (error) {
6 console.error('Error occurred:', error.message);
7}
8
9// Method 2: Try-catch with specific error
10try {
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}
19
20// Method 3: Try-catch-finally
21try {
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}
29
30// Method 4: Nested try-catch
31try {
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}
41
42// Method 5: Error object properties
43try {
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}
50
51// Method 6: Custom error handling
52function riskyOperation() {
53 if (Math.random() > 0.5) {
54 throw new Error('Random error');
55 }
56 return 'Success';
57}
58
59try {
60 const result = riskyOperation();
61 console.log('Result:', result);
62} catch (error) {
63 console.error('Operation failed:', error.message);
64}
65
66// 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}
78
79// Method 8: Error in async function
80async 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 needed
88 }
89}
90
91asyncOperation().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 fetch

What'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