Sunday, January 27, 2013

Exception Handling


How Exception Handling works?

At low level an exception is a java object with attributes and methods. When a problem occurs, an exception object is created, thrown and then handled.


exception handling can be grouped into these four phases. When a problem occurs it is the start of exception handling flow. A problem can be broadly classified into two. First one is, it can be handled and execution can continue, the second one is an unrecoverable serious situation which cannot be handled. An example for recoverable problem is, code block is expecting a value in a variable and it is not present. This can be handled by substituting a default value and the execution can continue. An easy example for unrecoverable condition is a hardware failure.

Java’s exception handling mechanism is object oriented. We have Throwable as the base class and all exceptions are sub classes of Throwable. We have Error and Exception as two immediate sub classes of Throwable.

When to use Exception Handling?

Exception handling should be used judiciously. Earlier I wrote about fail fast vs fail safe and that article loosely relates to this context and my personal preference is to fail fast. Exception handling does not mean that we should take the program flow in an alternate direction than the intended one and which may cause issues in future. We should be cautious when we say handling, as in the name of handling, an issue should not be carried over to a different context of the program as it will come back to haunt us.

So when do we use exception handling, it is when we foresee that a problem may occur at run time and we know a possible solution to it at design time itself. Then at run time if that solution path is chosen it should not alter the core objective of the program. Cases like, just logging the problem and proceeding with the flow does not fit into exception handling. A popular mistake done by java developers is to use exception handling for flow control. Though we have if-else and other options, we tend to fall on exception handling side and use it as flow control mechanism which is poor.

Exception Handling Keywords

throw

Exceptions can be thrown by either java run time environment or by the code itself. JRE throws exception when java’s rules are violated. An example is, when the code accesses an array location which is not available then ArrayIndexOutOfBoundsException is thrown. Pretty nice name right and obviously it explains the problem. All the java exception classes are not having any attributes and standard methods. It is a common design. Class name describes what exception it is and the hierarchy forms an organization chart kind of structure using which java exceptions are used.

Programmers can throw an exception to indicate a problem condition. Either java’s predefined exceptions can be used or custom exceptions can be created by extending the already available exceptions. Programmer can throw a custom exception or a predefined Java exception. Mostly custom exceptions are created based on business conditions. Programmer can use the Java keyword ‘throw‘ to generate an exception. It is done by instantiating the exception class of choice and then thrown.

try – catch

A thrown exception should be handled. If the program does not handles an exception, then it will be handled by the java run time environment. A block of code where an exception is expected should be surrounded by try – catch block. try indicates the start of the exception handling block and catch the end of the block. Following catch a block of code can be written which is the exception handling code block. This is the part the handles the exception. A catch will have an exception identified and it will catch only that type of exception. Type means the same exception and all its sub classes. There can be multiple catch blocks for a try block.

throws

When a Java method is going to throw an exception, to indicate that as part of the method signature ‘throws‘ keyword should be used followed by the exception. It means that the caller of this method should handle the exception given in the throws clause. There can be multiple exceptions declared to be thown by a method. If the caller of that method does not handles the exception, then it propagates to one level higher in the method call stack to the previous caller and similarly till it reaches base of the method call stack which will be the java’s run time system.

finally

After catch block there can be one more block of code declared as ‘finally‘. Irrespective of whether an exception is thrown or not, the finally block of code will always be executed. Important piece of code that must be executed, even if a program fails belong to this finally block. Example would be closing a database connection, a file handle, etc.

General Exception Handling Structure

try {
  // possible exception code block
} catch (ExceptionTypeA exception1) {
  // handle exception of type ExceptionTypeA and all it subclasses
} catch (ExceptionTypeB exception2) {
  // handle exception of type ExceptionTypeB and all it subclasses
} finally {
  // guarantee block: executes always irrespective of exception 
}

No comments:

Post a Comment

Creating mirror of BST