Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try {} without catch {} possible in JavaScript?

People also ask

Does every try need a catch?

Yes you can write try without catch. In that case you require finally block. Try requires either catch or finally or both that is at least one catch or finally is compulsory.

How will you come out of try {} block?

The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement: public void someMethod() { try { ... if (condition) return; ... } catch (SomeException e) { ... } }

Which statement is true about catch {} blocks?

Explanation: finally block is always executed after tryblock, no matter exception is found or not. catch block is executed only when exception is found.

Can we use catch () without passing arguments in it?

Some exception can not be catch(Exception) catched. Below excecption in mono on linux, should catch without parameter. Otherwise runtime will ignore catch(Exception) statment.


A try without a catch clause sends its error to the next higher catch, or the window, if there is no catch defined within that try.

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

try {
    // whatever;
} finally {
    // always runs
}

It's possible to have an empty catch block, without an error variable, starting with ES2019. This is called optional catch binding and was implemented in V8 v6.6, released in June 2018. The feature has been available since Node 10, Chrome 66, Firefox 58, Opera 53 and Safari 11.1.

The syntax is shown below:

try {
  throw new Error("This won't show anything");
} catch { };

You still need a catch block, but it can be empty and you don't need to pass any variable. If you don't want a catch block at all, you can use the try/finally, but note that it won't swallow errors as an empty catch does.

try {
  throw new Error("This WILL get logged");
} finally {
  console.log("This syntax does not swallow errors");
}

Nope, catch (or finally) is try's friend and always there as part of try/catch.

However, it is perfectly valid to have them empty, like in your example.

In the comments in your example code (If func1 throws error, try func2), it would seem that what you really want to do is call the next function inside of the catch block of the previous.


I wouldn't recommend try-finally without the catch, because if both the try block and finally block throw errors, the error thrown in the finally clause gets bubbled up and the try block's error is ignored, in my own test:

try {
  console.log('about to error, guys!');
  throw new Error('eat me!');
} finally {
  console.log ('finally, who cares');
  throw new Error('finally error');
}

Result:

>     about to error, guys!
>     finally, who cares
>     .../error.js:9
>         throw new Error('finally error');
>         ^
>     
>     Error: finally error