How to check which exception type was thrown in Java?
If Multiple throws
are happening in a single catch()
then to recognize which Exception , you could use instanceof
operator.
The java instanceof
operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
Try this code :-
catch (Exception e) {
if(e instanceof NotAnInt){
// Your Logic.
} else if if(e instanceof ParseError){
//Your Logic.
}
}
Use multiple catch
blocks, one for each exception:
try {
int x = doSomething();
}
catch (NotAnInt e) {
// print something
}
catch (ParseError e){
// print something else
}
If anyone didn't know what type of exception was thrown in the method e.g a method with a lot of possibilities like this one :
public void onError(Throwable e) {
}
You can get the exception class by
Log.e("Class Name", e.getClass().getSimpleName());
In my case it was UnknownHostException
then use instanseof
as mentioned in the previous answers to take some actions
public void onError(Throwable e) {
Log.e("Class Name", e.getClass().getSimpleName());
if (e instanceof UnknownHostException)
Toast.makeText(context , "Couldn't reach the server", Toast.LENGTH_LONG).show();
else
// do another thing
}
If you can, always use separate catch
blocks for individual exception types, there's no excuse to do otherwise:
} catch (NotAnInt e) {
// handling for NotAnInt
} catch (ParseError e) {
// handling for ParseError
}
...unless you need to share some steps in common and want to avoid additional methods for reasons of conciseness:
} catch (NotAnInt | ParseError e) {
// a step or two in common to both cases
if (e instanceof NotAnInt) {
// handling for NotAnInt
} else {
// handling for ParseError
}
// potentially another step or two in common to both cases
}
however the steps in common could also be extracted to methods to avoid that if
-else
block:
} catch (NotAnInt e) {
inCommon1(e);
// handling for NotAnInt
inCommon2(e);
} catch (ParseError e) {
inCommon1(e);
// handling for ParseError
inCommon2(e);
}
private void inCommon1(e) {
// several steps
// common to
// both cases
}
private void inCommon2(e) {
// several steps
// common to
// both cases
}