I read in the documentation of Precise Rethrow
that, http://www.theserverside.com/tutorial/OCPJP-Use-more-precise-rethrow-in-exceptions-Objective-Java-7
Basically, you can list specific exceptions in the throws clause of your method, even if they are not explicitly handled by a catch block if:
The try block actually throws that specific exception at some point in time.
The specific Exception isn't already handled at any point by a preceding catch block
The exception named in the throws clause of the method signature must be on the class hierarchy of at least one exception being handled and rethrown by a catch block (subtype or supertype)
Have a look at the code (attention on throws clause of main
)
class OpenException extends Exception {}
class CloseException extends Exception {}
public class PRethrow
{
public static void main(String args[]) throws OpenException, CloseException, java.io.IOException
{
boolean flag = true;
try
{
if (flag)
{
throw new OpenException();
}
else
{
throw new CloseException();
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
throw e;
}
}
}
It is clearly mentioned in the first condition that, you can list a specific exception in throws clause if the try block actually throws that specific exception at some point in time.
In my code the try block never throws java.io.IOException
, but still including it in throws clause produce no error.
The quote you mention is misleading:
throws
clause of a method, whether it can actually be thrown or not.For example this compiles: