Languages
[Edit]
EN

JavaScript - try / catch statement

3 points
Created by:
Palpys
764

In this article, we would like to show you how to use try / catch statement in JavaScript.

Introduction

Edit

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 the try 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

Edit
Syntax / exampleDescription
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 catch block but forwarded.

Finally block always executes after a try block.

Practical examples

Edit

Try... catch block

Edit

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:

Throw statement

Edit

In this section, we present how to throw a custom error (throw exception) using throw statement.

Note:

You can throw different types of exceptions.

Finally statement

Edit

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.

2. When exception isn't thrown you can see the finally block message in the console.

3. When exception is thrown but not catched, the finally block will still execute.

References

Edit
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Statements & declarations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join