Try Without Catch In JavaScript (Updated for 2023)

If you want to try some code and not handle the exception, it can seem annoying that you have to include a catch:

try { throw new Error(); } catch (e) { // ignore error }
Code language: JavaScript (javascript)

ES2019 (released in 2019) allows us to simplify the above code a bit with optional catch binding in which the error variable does not need to be specified:

try { throw new Error(); } catch { }
Code language: JavaScript (javascript)

Currently, this is the shortest way to catch and ignore an error in JavaScript.

Technically, it is possible to have a try without a catch, but you would be required to have a finally and it might not do what you are expecting.

try { throw new Error(); } finally { // the Error will still be thrown! }
Code language: JavaScript (javascript)

In the above code, the Error will still be thrown.

So, if you are wanting to run code and ignore an error you must use catch.


Posted

in

by

Tags:

Comments

Leave a Reply

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