Reputation: 59365
When I do something like this:
let resolved = null;
try {
resolved = require.resolve(modulePath)
} catch (e) {
}
I am wondering if there's a shorter syntax something like:
let resolved = null;
try resolved = require.resolve(modulePath)
Is there any way to forgive this line without opening up a catch block?
There's something like this but I'm looking for something more natural:
function t (fn, def) {
let resolved = def;
try {
resolved = fn()
} catch (e) {
}
return resolved;
}
Upvotes: 6
Views: 1302
Reputation: 64923
As other answerers have already pointed out, you either need to provide catch
or finally
.
BTW, what's wrong with implementing a high-order function?
const valueOrNull = f => {
try {
return f ()
} catch (e) {
return null
}
}
const output1 = valueOrNull (() => { throw Error () })
const output2 = valueOrNull (() => "hello world")
console.log ('output1', output1)
console.log ('output2', output2)
Upvotes: 0
Reputation: 183321
No; it's intentional that JavaScript try
-blocks must have either catch
or finally
. From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#Description:
The
try
statement consists of atry
block, which contains one or more statements.{}
must always be used, even for single statements. At least onecatch
clause, or afinally
clause, must be present.
(And note that try { ... } finally { }
, with no catch
, does the opposite of what you want: you want everything to be caught and swallowed, whereas try { ... } finally { }
doesn't catch anything.)
In your case, I think the best way to write it is:
let resolved;
try {
resolved = require.resolve(modulePath);
} catch (e) {
resolved = null;
}
which makes clear that resolved == null
is the error-case.
(Better yet — add some logic to make sure that the exception you've caught is really the one you're expecting. You probably don't want to silently swallow exceptions that result from unintended bugs!)
Upvotes: 5
Reputation: 1691
Is there any way to forgive this line without opening up a catch block?
Yes, if you implement a finally
clause.
Other than that, no.
A try is always accompanied by either a catch
or a finally
.
Upvotes: 2