Breakthrough Java exception handling rules (1)
Q: I am in my call in the application of external methods and capture it might be thrown to the abnormal. I can catch java.lang.Exception?
A: Through a given means to deal with all run-time anomaly detection and prevention for external error is not sufficient.
You can now must struggle JavaWorld article - "Java Tip 134: When Catching Exception, Don't Cast Your Net Too Wide." This article warned that the capture java.lang.Exception and java.lang.Throable is not good. Can you capture the abnormal designated for the maintainability of the code is very important. Nevertheless, the rules depend on special environment. If you do not intend to your program crashes and you retain the security of the data structure abnormalities, then you must capture was thrown out of the real anomalies.
For example, imagine you have a load of this interface server applications:
Public interface IFoo
(
/ **
* This method can't throw any checked exceptions ... or can it?
* /
Void bar ();
) / / End of interface
For the reasons given parameters is to inform you that we have the services in place, and different IFoo from external resources to achieve the load. 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' ...
)
In this, and you deal with all possible anomalies. Here, you do not catch java.io.IOException plus any abnormal because IFoo did not realize IFoo.bar () dished out it, right? (In fact, if you add the catch java.io.IOException abnormal block, the compiler may not arrive as it will be discarded abnormal)
Wrong. I wrote in the category EvilFoo bar () method that will throw you the type constructor transmitted to any unusual:
Public void bar ()
(
EvilThrow.throwThrowable (m_throwthis);
)
Main operations:
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 from the bar () method java.io.IOException dished out by examples and in the absence of any abnormal catch block:
Tags: exception, java Exception






