What does the try...catch construct do?
General idea
try...catchexists so that code does not "crash" on an error, and instead reacts to it in a controlled way: show a message, retry the action, log it, and so on.
Syntax
javascript
try {
// code where an error can occur
} catch (error) {
// code that runs if an error occurred
}How it works
- The code in the
tryblock runs line by line. - If an error occurs inside
try, execution oftrystops, and control passes tocatch. - If there are no errors, the
catchblock is skipped. - After
try...catch, the program keeps running.
Example 1. Without try...catch, the program crashes
javascript
console.log("Start");
JSON.parse("invalid JSON"); // SyntaxError
console.log("End"); // does not runOutput:
javascript
Uncaught SyntaxError: Unexpected token i in JSONExample 2. With try...catch, the program keeps running
javascript
console.log("Start");
try {
JSON.parse("invalid JSON");
} catch (err) {
console.log("Error caught:", err.message);
}
console.log("End");Output:
javascript
Start
Error caught: Unexpected token i in JSON at position 0
EndThe error is handled, and the program did not crash.
The finally block (optional)
You can add a third block, finally. It always runs, regardless of whether there was an error.
javascript
try {
console.log("Running try");
throw new Error("Error!");
} catch (err) {
console.log("Caught:", err.message);
} finally {
console.log("This code runs no matter what");
}Output:
javascript
Running try
Caught: Error!
This code runs no matter what
finallyis often used for cleaning up resources: closing a connection, stopping a timer, deleting temporary files, and so on.
Can be used with throw
try...catch is often used together with the throw operator to manually throw an exception:
javascript
function divide(a, b) {
if (b === 0) throw new Error("Division by zero!");
return a / b;
}
try {
console.log(divide(10, 0));
} catch (e) {
console.log("Error:", e.message);
}Behavior details
| Behavior | Description |
|---|---|
catch catches only runtime errors | Syntax errors (SyntaxError during code parsing) are not caught |
An error inside catch is not caught by the same try | It needs to be wrapped in a second try...catch |
try...catch can be nested | Different types of errors can be handled at different levels |
Example 3. Nested try...catch
javascript
try {
try {
throw new TypeError("Wrong type");
} catch (e) {
console.log("Inner catch:", e.message);
throw new Error("New error");
}
} catch (e) {
console.log("Outer catch:", e.message);
}Output:
javascript
Inner catch: Wrong type
Outer catch: New errorSummary
| Element | Purpose |
|---|---|
try | Code where an error is possible |
catch | Handles the error, if one occurred |
error | The variable holding the error object |
finally | Always runs, after try/catch |
throw | Generates an exception that catch catches |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.