Q: I called an external method in my application and wanted to catch the exception it might throw. Can I capture java.lang.Exception?
A: Handling all runtime and detection exceptions in a given way is not sufficient to prevent external errors.
You can read the current Javaworld article – "Java Tip 134:when catching Exception, Don ' t Cast Your Net Too Wide". This article warns that capturing java.lang.Exception and java.lang.Throable is not good. Capturing the exceptions you can specify is important for the maintainability of your code. However, this rule relies on special circumstances. If you are not going to crash your program and keep your data structure safe, you must capture the real exception that is thrown.
For example, imagine that you have a server application that loads this interface:
public interface IFoo
{
/**
* This method can't throw any checked exceptions...or can it?
*/
void bar ();
} // End of interface
The reason for giving arguments is to let us inform you where such services are, and different IFoo implementations can be loaded from external resources. You write the following code:
try
{
IFoo foo = ... // get an IFoo implementation
foo.bar ();
}
catch (RuntimeException ioe)
{
// Handle 'ioe' ...
}
catch (Error e)
{
// Handle or re-throw 'e' ...
}
And you handled all the possible anomalies in this. You do not need to add any exception to the catch java.io.IOException here, because the IFoo implementation does not throw it from Ifoo.bar (), right? (In fact, if you add a catch Java.io.IOException exception block, the compiler might discard it as an unreachable exception)
Error. In the Evilfoo Class I wrote, the Bar () method proves to throw any exceptions you pass to the Class Builder:
public void bar ()
{
EvilThrow.throwThrowable (m_throwthis);
}
To run the Main method:
public class Main
{
public static void main (final String[] args)
{
// This try/catch block appears to intercept all exceptions that
// IFoo.bar() can throw; however, this is not true
try
{
IFoo foo = new EvilFoo (new java.io.IOException ("SURPRISE!"));
foo.bar ();
}
catch (RuntimeException ioe)
{
// Ignore ioe
}
catch (Error e)
{
// Ignore e
}
}
} // End of class
You will see a Java.io.IOException exception instance thrown from the bar () method and no capture block:
>java -cp classes Main
Exception in thread "main" java.io.IOException: SURPRISE!
at Main.main(Main.java:23)