Try-Catch-Finally in JavaScript
Learn try, catch and finally in JavaScript: catch JSON errors, nest blocks, read error name and stack, and handle async errors. Explanation and output.
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});
Sample Output
Result: Infinity
Dividing by zero is not an error in JavaScript, so catch does not run.
Operation failed: Random error
Math.random decides this line. About half the time you will see Result: Success instead.
Async error: Failed to fetch
The example URL is not a real API, so fetch fails. It prints last because fetch finishes after all the normal code. Node shows "fetch failed" instead.
In this one
- How try, catch and finally work together
- Why 10 / 0 does not throw an error
- How to check an error type with instanceof
- How to catch errors from await
How it works
- 1
10 / 0 gives Infinity, so Method 1 prints the result.
- 2
JSON.parse throws a SyntaxError, and catch prints its message.
- 3
Method 3 prints Trying..., the caught message, then the finally line.
- 4
The nested try passes a new error to the outer catch.
- 5
Method 5 prints the name, message and stack.
- 6
Method 6 prints success or failure at random.
- 7
Method 7 sees a TypeError and prints it.
- 8
Method 8 fails to fetch and prints two lines at the end.
Edge cases
Errors in a callback
A setTimeout callback throws, and the outer try does not catch it.
try only covers code that runs right now. Put a try inside the callback.
Throwing a string
throw "oops" gives a catch value with no message or stack.
Always throw new Error("oops") so you get name, message and stack.
return inside finally
A return in finally replaces the value returned by try.
Use finally only for clean-up, not for returning values.
What's going on
A program can hit a problem while it runs. A user types bad data, or a server does not answer. Without a plan, the error stops the whole script. In JavaScript, try and catch give you that plan.
You put risky code inside try. If any line throws an error, JavaScript jumps straight to catch. "Throw" means to stop normal work and report a problem. The catch block gets the error object, so you can read error.message and react.
Method 1 is a trap. 10 / 0 does not throw in JavaScript. It returns Infinity, so the catch block never runs. Only real errors, like JSON.parse('invalid json'), reach catch. Method 2 uses instanceof, which checks what kind of error it is. JSON.parse throws a SyntaxError.
The finally block runs every time, with or without an error. Use it for clean-up work, like hiding a loading spinner.
Method 4 shows a nested try. The inner catch handles its error, then throws a new one, and the outer catch gets that new error. Method 5 prints name, message and stack. The stack is a list of the function calls that led to the error.
JavaScript has only one catch per try. Method 7 checks the error type with if and else instead. Method 6 uses Math.random, so it prints a success or a failure at random.
Method 8 uses await inside an async function. A failed fetch throws there, so try and catch work the same way. The function logs the error and throws it again, so the caller's .catch also runs. That is why two async lines print last.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does 10 / 0 do in JavaScript?
Pick an answer to check it.
Question 2
When does the finally block run?
Pick an answer to check it.
Question 3
Which error does JSON.parse("abc") throw?
Pick an answer to check it.
Questions people ask
Does finally run after a return in try?
Yes. finally runs before the function actually returns.
Can I leave out the catch block?
Yes. try with only finally is allowed. The error still goes up to the caller.
Why is the JSON error message different in my browser?
Each browser writes its own message text. The error type, SyntaxError, stays the same.