In Java, is there any way to get(catch) all exceptions
instead of catch the exception individually?
Catch the base exception 'Exception'
try {
//some code
} catch (Exception e) {
//catches exception and all subclasses
}
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.
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 other exceptions
).
The code looks like:
public void someMethode() throws SomeCheckedException {
// code
}
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)
try {
// exceptional block of code ...
// ...
} catch (Exception e){
// Deal with e as you please.
//e may be any type of exception at all.
}
The reason that works is because Exception
is the base class for all exceptions. Thus any exception that may get thrown is an Exception
(Uppercase 'E').
If you want to handle your own exceptions first simply add a catch
block before the generic Exception one.
try{
}catch(MyOwnException me){
}catch(Exception e){
}
Yes there is.
try
{
//Read/write file
}catch(Exception ex)
{
//catches all exceptions extended from Exception (which is everything)
}
You may catch multiple exceptions in single catch block.
try{
// somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
// handle exception.
}
Do you mean catch an Exception
of any type that is thrown, as opposed to just specific Exceptions?
If so:
try {
//...file IO...
} catch(Exception e) {
//...do stuff with e, such as check its type or log it...
}