问题
I was wondering if there is a way to not specify the argument when doing a JS try/catch. Every time I try this though, the try/catch doesn't work.
The working version:
try{
//Breaking code
} catch(e){
//Nothing happens here
}
What I have in mind (No 'e'):
try{
//Breaking code
} catch(){
//Nothing happens here
}
回答1:
You just can't. The spec says that there must always be an identifier inside parens after catch
.
回答2:
Optional catch binding in 2019
Node.js
In Node.js, this feature is called Optional Catch Binding and is supported since Node.js version 10.3, see https://node.green.
Typescript
In Typescript, this is allowed since version 2.5.
Browser support
- Chrome: since 68
- Firefox: since 58
- Edge, IE, Safari: no support for now
Standard
The proposal is currently Stage 4, meaning that its implementation is finished and it is guaranteed to be included into the next version of the ECMAScript standard.
So this is a perfectly legitimate syntax now according to the standard if you are using Node.js or transpiling your browser code using Babel:
try {
} catch {
// No need for the `(error)` after `catch`!
}
回答3:
The specification gives the grammar for a catch block:
Catch :
catch (
Identifier)
Block
And goes on to state that:
When a catch clause catches an exception, its Identifier is bound to that exception
So it is a syntax error to omit the identifier from a catch
block.
回答4:
Simply omit the parenthese, like this:
try {
// Code...
} catch {
// Code...
}
回答5:
Agreed, it's mandatory so that you can handle the error fully - even if you know what the error is likely to be. In truth, just prod in a variable name and don't use it within your catch routine :)
来源:https://stackoverflow.com/questions/21624456/can-i-use-a-try-catch-in-javascript-without-specifying-the-catch-argument-identi