The cost of exception handling


In the example used earlier to illustrate application exceptions, we are checking if withdrawal amount is greater than balance to throw the exception. This is not something you should be doing every time. Exceptions are expensive and should be used exceptionally. In order top understand some of the issues involved; let us look at the mechanism used by the Java Virtual Machine (JVM) to handle the exceptions. The JVM maintains a method invocation stack containing all the methods that have been invoked by the current thread in the reverse order of invocation. In other words, the first method invoked by the thread is at the bottom of the stack and the current method is at the top. Actually it is not the actual method that is present in the stack. Instead a stack frame representing the method is added to the stack. The stack frame contains the method ‚ s parameters, return value, local variables and JVM specific information. When the exception is thrown in a method at the top of the stack, code execution stops and the JVM takes over. The JVM searches the current method for a catch clause for the exception thrown or one of the parent classes of the thrown exception. If one is not found, then the JVM pops the current stack frame and inspects the calling method (the next method in the stack), for the catch clause for the exception or its parents. The process continues until the bottom of the stack is reached. In summary, it requires a lot of time and effort on the part of JVM.

Exceptions should be thrown only when there is no meaningful way of handling the situation. If these situations (conditions) can be handled programmatically in a meaningful manner, then throwing exceptions should be avoided. For instance if it is possible to handle the problem of withdrawal amount exceeding the balance in some other way, it has to chosen over throwing an application exception.

Examples of SystemException can be a ConfigurationException , which might indicate that the data load during start up failed. There is really nothing a user or even the customer support could do about it, except to correct the problem and restart the server. Hence it qualifies as a System exception and can be modeled as runtime exception.

Certain exceptions like SQLException might indicate a system error or application problem depending on the case. In either case, it makes a lot of sense to model SQLException as a checked exception because that is not thrown from your application logic. Rather it is thrown in the third party library and the library developer wants you to explicitly handle such a scenario.




Struts Survival Guide. Basics to Best Practices
Struts Survival Guide: Basics to Best Practices (J2ee Survival Series)
ISBN: 0974848808
EAN: 2147483647
Year: 2004
Pages: 96

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net