You can manage an exception within a method using try
and catch
as you say. In that case, you do not need to use throws
. For example:
public void myMethod()
{
try {
/* Code that might throw an exception */
}
catch (SpaceInvadersException exception) {
/* Complicated error handling code */
}
}
But suppose you had a thousand methods, all of which might throw a SpaceInvadersException
. Then you would end up having to write all the complicated error handling code a thousand times. Of course, you could always create an ErrorHandler
class with a dealWithSpaceInvadersException()
method that you could call from them, but you'd still be stuck with a thousand try
-catch
blocks.
Instead, you tell the compiler that each of these thousand methods could throw a SpaceInvadersException
. Then any method that calls one of these methods needs to deal with the error itself, either by using a try
-catch
, or by telling the compiler that it might throw a SpaceInvadersException
. This is done using the throws
keyword, like this:
public void myMethod() throws SpaceInvadersException
{
/* Code that might throw an exception */
}
public void callingMethod()
{
try {
myMethod();
}
catch (SpaceInvadersException exception) {
/* Complicated error handling code */
}
}
In that case, you need to inform the compiler that myMethod
could throw a SpaceInvadersException
. This means that you can't call that method without dealing with the exception in some way (try
-catch
or using the throws
keyword on the calling method). If throws
weren't there, you could call the method without doing any exception handling, and get an exception that wasn't dealt with anywhere in the program (which would be bad).
Since it is always better to avoid code duplication, it is normally better to palm off your error handling to a try
-catch
in a much higher level function than it is to deal with it separately in all of the low level methods. That is why this mechanism exists.