Omitting the catch block for the try expression

Like this question, what is the reason behind forcing either a catch block or a finally block (or both) to be present after a try block?

If there are no specific reasons, the following should be proposed.

// No catch block
try {
	throw new Error("error");
}
// Alternative syntax to optional catch binding
try {
	throw new Error("error");
} catch () {}
// Both equivalent to
try {
	throw new Error("error");
} catch (_) {}
// and (optional catch binding)
try {
	throw new Error("error");
} catch {}

The omission of a catch of finally block seems far more likely to be a bug than intentional - what you propose would mean that bug silently swallowed an error.

3 Likes

try { operation() } finally {} does not suppress errors. So try { operation() } can't reasonably do so either.

4 Likes

Can we define it despite its reasonableness, or possibly create a new syntax instead?

It would be great and enough if I could use a semicolon to replace an empty catch block, like try { /* … */ } catch; though.

The issue is that this proposed syntax addition is encouraging a bad practice, namely, taking any errors that occurred within the block and silencing them. Why would you want to do that? If there's a specific error that you're expecting, then catch that specific error and silence it. Re-throw all others. If you're not sure what errors you should expect, then you'll just have to figure it out. If you catch and silence everything, then you risk accidentally catching actual bugs and silencing those too, and that would be an extremely difficult situation to debug.

4 Likes

This is only 2 characters shorter than catch {}. Though this does sometimes get longer when working on a codebase with a linting rule against empty blocks. However I tend to leave a comment to assure the reader that this is intentional.

catch { \* ignore exceptions *\ }

3 Likes

That linting rule is also satisfied with catch {/**/}, if you’re going for brevity.

3 Likes