try/catch
- Node.js course
- Intermediate
- Lesson 77/116
- 5 min
Learn to catch errors with try/catch.
try/catch
try/catch is the way to safely run code that may throw an error. If code in the try block throws, the flow jumps to the catch block where the error is handled.
For example, try { risky(); } catch (e) { console.log(e.message); } — if risky() throws an error, it is placed in e and the catch block runs. If there is no error, catch is skipped and normal flow continues. e is the thrown Error object; you can access e.message, e.stack and so on. This way the program keeps going on unexpected errors instead of crashing.
The catch variable
The e in catch (e) is the variable that holds the thrown error. You can name it anything; e, err and error are common choices.
This variable is only valid inside the catch block. With e instanceof Error you can check whether the thrown value is really an Error. You can also get the message with e.message and the call trace with e.stack. If a non-Error value is thrown, like throw "string", then e holds that value; that is why always throwing with new Error() is the best practice. This keeps the error object consistent.
Practice Throw and catch, print instanceof
Define a function named risky whose body is throw new Error("test"). Call risky() inside try. Inside catch (e) print console.log(e instanceof Error).
Starter code
// Define a risky function that throws an Error
// Call it in try, catch with catch
// Print instanceof Error
// write hereSample solution
function risky() {
throw new Error("test");
}
try {
risky();
} catch (e) {
console.log(e instanceof Error);
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the try block
____ { risky(); } catch (e) { console.log(e.message); }
try { risky(); } catch (e) { console.log(e.message); }
Explanation: The try block runs risky code.
2 Match each block to its role
| Term | Meaning |
|---|---|
try |
Runs risky code |
catch |
Catches the error |
throw |
Throws an error |
e |
The caught error |
3 What happens if no error is thrown in the try block?
try { ... } catch (e) { ... }- The catch block is skipped, normal flow continues Correct answer
- The program crashes
- catch still runs
- An error is thrown
Explanation: With no error, catch is skipped.