Exception Handling – Part I

Java has many wonderful things and exception handling is one among them. Exception handling is a framework provided by Java to ensure program execution continues in an unfavorable problem condition by handling it gracefully. Exception handling is not new to Java guys and I need not give a heroic introduction to it. This is my attempt at writing a detailed tutorial like a chapter in a Java book, by giving comprehensive coverage to this topic accompanied by code examples, images, bells and whistles. I will give a simple and easy to understand narrative to java exception handling and try to uncover intricate detail as much as possible in my own style. As exception handling is a large topic, this will be a multi-part series.
I chose to use the word problem instead of error in the above definition. Error is a java class and given a specific meaning in Java exception handling and I didn’t want that to be mixed with the general English word which denotes an unfavorable condition. Google says, problem is “A matter or situation regarded as unwelcome or harmful and needing to be dealt with and overcome”. In general software terms we use error to signify that and they are of two types, compile time and run time. In exception handling we will be dealing only with run-time problems. In any software program, there are numerous possibilities that a problem can occur at run-time during the flow of execution. How it is handled is crucial to the business and user. Right from Ada to C++ to PHP exception handling is available.
Imagine if there is no exception handling mechanism available and what would happen if a run time error occurs. Most likely the program may crash in ugly manner resulting in an un wanted situation. In those situations, we can analyze the programs and use if-condition construct and try to salvage the situation. Repair the code and re-run it. Some problems cannot be handled and will result in reporting error code and abruptly discontinue the execution. All these will result in unorganized / non maintainable code. With Java’s exception handling mechanism we have an organized and simplified more importantly object oriented way of handling run-time problems.

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.
exceptionFlow
As shown in above figure, 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 trycatch 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
}
This is a multi-part tutorial series and continue reading the next part of exception handling tutorial.

0 comments:

Post a Comment