JavaScript - try / catch statement
In this article, we would like to show you how to use try / catch statement in JavaScript.
Introduction
There are four basic keywords related to the topic that you need to know:
try
- is used to test the code wrapped with curly braces ({}
) for errors,catch
- is executed if an exception is thrown in thetry
block,finally
- executes the code wrapped with curly braces after try... catch block regardless of the result,throw
- is used to create and throw custom errors.
try...catch...finally cases
Syntax / example | Description |
---|---|
| This solution catches exceptions that appear in the code in the try block. If the exception occurs, the catch is executed. |
| The same scenario as in the example above, with one difference - regardless of the exception being thrown (or not), the finally block will always be executed after the try and catch blocks. |
|
In this case, the exception is not caught by the Finally block always executes after a |
Practical examples
Try... catch block
In this example, we present how to create a simple try
block that throws an error and how to handle the error with the catch
block.
Practical example:
// ONLINE-RUNNER:browser;
try {
let x = y;
} catch (error) {
console.error(error); // ReferenceError: y is not defined
}
Throw statement
In this section, we present how to throw a custom error (throw exception) using throw
statement.
// ONLINE-RUNNER:browser;
try {
let x = 3;
if (x != 0) {
throw 'Custom error message.'
}
console.log('Try block executed.');
} catch (error) {
console.error(error); // Custom error message.
}
Note:
You can
throw
different types of exceptions.
Finally statement
In this section, we present three different cases of finally
block execution.
1. When exception is thrown you can see both messages in the console.
// ONLINE-RUNNER:browser;
try {
const x = 3;
if (x != 0) {
throw 'Custom error message.'
}
console.log('Try block executed.');
} catch (error) {
console.error(error);
} finally {
console.log('Finally block message (executed on success and exception).');
}
2. When exception isn't thrown you can see the finally
block message in the console.
// ONLINE-RUNNER:browser;
try {
// insert your code here...
console.log('Try block executed.');
} catch (error) {
console.error(error);
} finally {
console.log('Finally block message (executed on success and exception).');
}
3. When exception is thrown but not catched, the finally
block will still execute.
// ONLINE-RUNNER:browser;
try {
const x = 3;
if (x != 0) {
throw 'Custom error message.'
}
console.log('Try block executed.');
} finally {
console.log('Finally block message (executed on success and exception).');
}