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;
}
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.exit () it will execute always.
The classical way to program is with try ... catch. When is it appropriate to use trywithout catch? In Python the following appears legal and can make sense: try: #do work finally: #do something unconditional However, the code didn't catchanything. Similarly one could think in Java it would be as follows:
There is no way to compress a try / except block onto a single line in Python. Also, it is a bad thing not to know whether a variable exists in Python, like you would in some other dynamic languages. The safer way (and the prevailing style) is to set all variables to something.
This is basically how a try/catch is constructed. You put your code in the try block, and immediately if there is an error, JavaScript gives the catch statement control and it just does whatever you say. In this case, it alerts you to the error.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With