When something fails
Some operations can fail: reading data that does not exist, converting text
to a number, dividing by zero in an invalid way... If you do not handle it, an
error stops the program's execution. To handle it in a controlled way you
use the try...catch block.
try {
// code that may fail
const data = JSON.parse("this is not JSON");
} catch (error) {
// runs only if there was an error
console.log("Something went wrong:", error.message);
}
- The
tryblock contains the "risky" code. - If an error is thrown, control jumps to the
catchblock, which receives the error object. - If there is no error,
catchis ignored completely.
The finally block
It is optional and runs always, whether there was an error or not. It is used for cleanup tasks (closing connections, hiding a loading indicator...):
try {
doSomething();
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("This runs no matter what");
}
Examples
Catch an error and continue
function parse(text) {
try {
return JSON.parse(text);
} catch (error) {
console.log("Invalid JSON:", error.message);
return null;
}
}
console.log(parse('{"ok":true}'));
console.log(parse("not json"));