What I am trying to do feels counter intuitive, but Java keeps surprising me all the time, so I give it a shot.
I am implementing an application with the help of the ESAPI library. This library provides its own exceptions. In addition to the well known exception behavior those exceptions do things like automatic logging with log4j and providing information to an intrusion detection module.
Now I want to use these features in all parts of my application. Anytime a method of mine throws an exception, I don’t throw a normal exception but a selfmade exception that extends from the new EnterpriseSecurityException. Works like a charm.
But what can I do if I use a method, that throws a normal exception? Let’s say I want to read a file using an java.io.FileInputStream? It cannot find the file and throws a FileNotFoundException. Unfortunately the FileNotFoundException does not provide the features of my own Exceptions, because it does not extend the EnterpriseSecurityException.
Is there any trick in Java to change the exceptions a method throws? It sounds strange to me as I write this, but maybe someone can come up with a solution. The only idea I had so far is catching the normal exception, extract the relevant information, and build a new exception with it. But this seems pretty crude…
Catch the exception and throw a new one that extends from
EnterpriseSecurityExceptionand pass the old exception to the new one to chain them together.By chaining the exceptions you won’t lose the stack trace from the original exception.