JavaScript
try...catch basics
Learn to catch errors with try and catch and prevent the app from crashing.
try...catch basics
In JavaScript runtime errors crash the application. To prevent this you put risky code in a try block and error handling in a catch block. When an error occurs inside try, execution jumps straight to catch.
Example: try { riskyCode(); } catch (e) { console.error(e.message); }. Here the e parameter carries the error. If the error is not caught the browser writes a red error to the console and the rest of the code does not run.
The benefit of catching errors
The catch block catches the error and prevents the application from crashing. The parameter is usually named e or err; this object carries the error's message, name and stack information.
For example when you convert user input to a number, parseInt may fail. If you wrap this in a try and return a default value in catch, the application continues without interruption. Error handling lets you show a friendly warning instead of a breaking message to the user.
Exercise Safe division with try/catch
Define a function called divide. It should take a and b parameters. In the body open a try block and write return a / b inside it. In a catch (e) block call console.error(e.message) and return null. Then call divide(10, 0).
Show example solution
function divide(a, b) {
try {
return a / b;
} catch (e) {
console.error(e.message);
return null;
}
}
divide(10, 0);
Test yourself
-
Which is a valid try/catch structure?
- catch { riskyCode(); } try (e) { handleError(e); }
- try { riskyCode(); } catch (e) { handleError(e); }
- if (error) { try(); } else { catch(); }
- while (try) { catch(e); }
Show answer
try { riskyCode(); } catch (e) { handleError(e); } — Correct. try comes first, then catch, and catch takes a parameter.
-
Add the catch block
function safeDivide(a, b) {
try {
return a / b;
} ____(e) {
console.error("Error:", e.message);
return null;
}
}
Show answer
function safeDivide(a, b) {
try {
return a / b;
} catch(e) {
console.error("Error:", e.message);
return null;
}
}
-
Match try/catch situations to outcomes
- no error in try
- catch does not run
- error in try
- catch runs
- catch (e) parameter
- carries error info
- without try/catch
- app crashes
Next lesson: Throwing errors with throw