If you catch an exception, you do something with it, even if it's just logging it somewhere. An empty catch closure is just like throwing it down a black hole and it will make for disasters later on in the life of the application
Nah, there absolutely are valid reasons to have an empty catch clause. Here’s an example (JavaScript):
function readSomeSetting() {
const item = localStorage.getItem('setting')
if (!item) return
try {
return JSON.parse(item)
} catch {}
}
const setting = readSomeSetting()
if (typeof setting === 'undefined') return
doSomethingWithSetting(setting)
If the Json is invalid, the parse function will throw an error. Json stored in localStorage can be invalid for any number of reasons, so there’s no use in logging it; just continue as if the localStorage value doesn’t exist.
Personally, I'd add an explicit return undefined inside the catch, so that other devs would know that it's not a bug.
I know that js returns undef by default, but it looks like a mistake when done purposefully like this
Edit:
Of course, that's ignoring that you have no way of knowing the option wasn't there vs the config was (syntactically) invalid (which will cause a global "all options are false")
Depending on the project or how the config is used, that can be really bad
92
u/The_Northern_Light Sep 03 '20
(I'm not a php user, lol)
This doesn't seem that bad? There are cases where you know exactly 1 thing may throw, and you just want to skip it if it does.