Is it possible to figure out all possible exceptions that can be thrown that are not necessarily listed by the method’s signature.
There are 2 cases
1) runtime exceptions that don’t have to be declared (obviously some are obvious, such as null pointer, but there are other runtime exceptions that I’d want to catch that can be due to bad data, which while in development I don’t know is bad data yet).
2) exceptions that are subclasses of the exception listed in the signature.
a motivation example
imagine I call getInputStream() on an HttpURLConnection object, it throws java.io.Exception, but in reality, it throws other exceptions that are sublcasses of java.io.Exception (ala java.io.FileNotFoundException), which I’d want to handle in a unique manner (i.e. don’t want to lump all java.io.Exceptions together).
so while I can learn in practice by catching java.io.Exception and printing out the actual exception, and then modifying code to handle that case, was wondering if there was a better method 🙂
thanks
edit: I think people are missing my 2nd problem. Methods that throw checked exceptions that are fully consistent with the method’s signature, but aren’t listed in it due to the method’s signature only having some sort of base class.
No. You can’t know in principle ahead of time what exception classes will be present on the CLASSPATH at runtime, for a start, nor can you know ahead of time the possible set of classes that implement the interface you are looking at, or extend the class you are looking at and override the method, unless the class or method is final. Your own example is a perfect case in point: you are looking at
HttpURLConnection, but it is an abstract class, and the actual implementation class that appears at runtime can vary depending on your configuration: the HTTPURLStreamHandlerclass used can be redefined so as to use one that returns a different implementation ofHttpURLConnection.