Skip to content

JavaScript try without catch

  • by

In JavaScript, you can use a try statement without a corresponding catch clause. This is useful in situations where you want to execute some code that may throw an exception, but you don’t need to handle the exception directly.

If you do not have a catch, a try expression requires a finally clause.

try {
  // some code that may throw an exception
} finally {
  // some code that will always run
}

The finally block can be used to perform cleanup operations that need to be executed regardless of whether an exception was thrown.

JavaScript try without catch example

Simple example code of using try without catch and with finally:

<!DOCTYPE html>
<html>
  <body>
    <script>
        function divide(a, b) {
            let result;
            try {
                result = a / b;
            } finally {
                console.log("Division operation completed.");
            }
                return result;
            }
        console.log(divide(2,2))
        console.log(divide(1,0))
    </script>
  </body>
</html>

Output:

JavaScript try without catch

Note: we’re not handling exceptions directly in this example; instead, we’re relying on the fact that if an exception is thrown, the code in the finally block will still execute. If you need to handle exceptions directly, you’ll need to include a catch clause in your try block.

Comment if you have any doubts or suggestions on this JS exception handling the topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *