Throw Custom Exceptions In Java/android
Solution 1:
In addition to Eran's answer, you could also make your custom Exception extend RuntimeException
, which does not need to be caught.
Solution 2:
If the method that throws this exception doesn't handle it (i.e. it doesn't catch it), it must declare it in the throws
clause, since this is a checked exception.
publicvoidyourMethod () throws UserException
{
...
thrownew UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
...
}
Solution 3:
if your Custom Exception extends from Exception class, it must be handled (using try-catch
) or passed on to caller (using throws
). If you just want to leave it to runtime to handle the exception, You need to extend it from RuntimeException Class
Since its the 1st case in your scenario, You should do something like this:
publicvoidsurroundingMethod() throws UserException{
thrownew UserException("Something failed.", new Throwable(String.valueOf(UserExceptionType.CaptureFailed)));
}
this will essentially pass your exception to the caller, so now it will be caller's responsibility to handle it with try-catch or pass it on again.
so again, u need to modify calling instruction as
publicvoidcallingMethod () {
try {
surroundingMethod();
} catch (UserException ex){
}
}
Solution 4:
You should either declare your methods as throws UserException
- or make your exception extend RuntimeException
.
The later is officially unadvised, but is often used to bypass the java's declared exception mechanism.
Solution 5:
In Java, when you throw
a checkedException
, there is one more thing you are required to do:
1. Either add a try-catch
block around the throw
and handle this Exception
within the same method.
2. Or add a throws
statement to the method definition, transferring the responsibility for the handling of the the Exception
to a higher-level method.
This is part of the overall OOP paradigms of modularity & abstraction: who is responsible for handling an Exception
, the caller of a method or the method itself ? The answer depends on the nature of the Exception
.
Post a Comment for "Throw Custom Exceptions In Java/android"