In Java, is there any way to get(catch) all exceptions
instead of catch the exception individually?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Do you mean catch an
Exception
of any type that is thrown, as opposed to just specific Exceptions?If so:
If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the
exceptions
later (perhaps at the same time as otherexceptions
).The code looks like:
Then later you can deal with the
exceptions
if you don't wanna deal with them in that method.To catch all exceptions some block of code may throw you can do: (This will also catch
Exceptions
you wrote yourself)The reason that works is because
Exception
is the base class for all exceptions. Thus any exception that may get thrown is anException
(Uppercase 'E').If you want to handle your own exceptions first simply add a
catch
block before the generic Exception one.Catch the base exception 'Exception'
You may catch multiple exceptions in single catch block.
While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.
However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable
It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.
For most file operations, IOException is the root exception. Better to catch that, instead.