Exception Handling

An unwanted unexpected event that disturbs normal flow of the program is called exception.

Example:
SleepingException
TyrePunchuredException
FileNotFoundException …etc
It is highly recommended to handle exceptions. The main objective of exception handling is graceful (normal) termination of the program.

What is the meaning of exception handling?

Exception handling doesn’t mean repairing an exception.We have to define alternative way to continue rest of the program normally. This way of defining alternative is nothing but exception handling.

Example:
Suppose our programming requirement is to read data from remote file locating at London. At runtime if London file is not available then our program should not be terminated abnormally.
We have to provide a local file to continue rest of the program normally. This way of defining alternative is nothing but exception handling.

Example:

Runtime Stack Mechanism

For every thread JVM will create a separate stack at the time of Thread creation. All method calls performed by that thread will be stored in that stack. Each entry in the stack is called “Activation record” (or) “stack frame”.

After completing every method call JVM removes the corresponding entry from the stack. After completing all method calls JVM destroys the empty stack and terminates the program normally.

Default Exception Handling in Java:

1. If an exception rose inside any method then that method is responsible to create Exception object with the following information.
i. Name of the exception.
ii. Description of the exception.
iii. Location of the exception. (Stack Trace)
2. After creating that Exception object, the method handovers that object to the JVM.
3. JVM checks whether the method contains any exception handling code or not. If method won’t contain any handling code then JVM terminates that method abnormally and removes corresponding entry form the stack.
4. JVM identifies the caller method and checks whether the caller method contain any handling code or not. If the caller method also does not contain handling code then JVM terminates that caller method also abnormally and removes corresponding entry from the stack.
5. This process will be continued until main method and if the main method also doesn’t contain any exception handling code then JVM terminates main method also and removes corresponding entry from the stack.
6. Then JVM handovers the responsibility of exception handling to the default exception handler.
7. Default exception handler just print exception information to the console in the following format and terminates the program abnormally.

Exception in thread “xxx(main)” Name of exception:
description
Location of exception (stack trace)

Output:
Exception in thread “main’ java.lang.ArithmeticException: /
by zero
atTest.doMoreStuff(Test.java:1O)
atTest. doStuff(Test.java:7)
atTest.main(Test.java:4)

Exception Hierarchy

Throwable acts as a root for exception hierarchy. Throwable class contains the following two child classes.

Exception:

Most of the cases exceptions are caused by our program and these are recoverable.
Ex: If FileNotFound Exception occurs then we can use local file and we can continue rest of the program execution normally.

Error:

Most of the cases errors are not caused by our program these are due to lack of system resources and these are non-recoverable.

Ex: If OutOfMemoryError occurs being a programmer we can’t do anything the program will be terminated abnormally. System Admin or Server Admin is responsible to raise/increase heap memory.

Checked Vs Unchecked Exceptions:

• The exceptions which are checked by the compiler whether programmer handling or not, for smooth execution of the program at runtime, are called checked exceptions.
1. HailTicketMissing Exception
2. PenNotWorkingException
3. FileNotFoundException

• The exceptions which are not checked by the compiler whether programmer handing or not, are called unchecked exceptions.
1. ArithmeticException
2. NullPointerException

Note:
RuntimeException and its child classes, Error and its child classes are unchecked and all the remaining are considered as checked exceptions.Whether exception is checked or unchecked compulsory it should occurs at runtime only and there is no chance of occurring any exception at compile time.

Fully checked Vs Partially checked:

A checked exception is said to be fully checked if and only if all its child classes are also checked.

Example:
1) IOException
2) InterruptedException
A checked exception is said to be partially checked if and only ¡f some of its child classes are unchecked.

Example:
Exception

Note:
The only possible partially checked exceptions in java are:
1. Throwable.
2. Exception.

Q: Describe behavior of following exceptions?
1. RuntimeException— unchecked
2. Error—–unchecked
3. IOException- fully checked
4. Exception partially checked
5. InterruptedException fully checked
6. Throwable partially checked
7. ArithmeticException unchecked
8. NullPointerException – unchecked
9. FileNotFoundException fully checked

Customized Exception Handling by using try-catch:

• It is highly recommended to handle exceptions.
• In our program the code which may raise exception is called risky code, we have to place risky code inside try block and the corresponding handling code inside catch block.

Example:

Control flow in try catch

Case 1:
If there is no exception.
1, 2, 3, 5 normal termination.

Case 2:
If an exception raised at statement 2 and corresponding catch block matched 1, 4, 5 normal termination.

Case 3:
If an exception raised at statement 2 but the corresponding catch block not matched 1 followed by abnormal termination.

Case 4:
If an exception raised at statement 4 or statement 5 then it’s always abnormal termination of the program.

Note:
1. Within the try block if anywhere an exception raised then rest of the try block won’t be executed even though we handled that exception. Hence we have to place/take only risk code inside try block and length of the try block should be as less as possible.
2. If any statement which raises an exception and it is not part of any try block then it is always abnormal termination of the program.
3. There may be a chance of raising an exception inside catch and finally blocks also in addition to try block.

Various methods to print exception information:

Throwable class defines the following methods to print exception information to the console.

printStackTrace():
This method prints exception information in the following format.
Name of the exception: description of exception Stack trace.

toString():
This method prints exception information in the following format.
Name of the exception: description of exception getMessage():
This method returns only description of the exception Description.

Note:
Default exception handler internally uses printStackTrace()method to print exception information to the console.

Try with multiple catch blocks:

The way of handling an exception is varied from exception to exception. Hence for every exception type it is recommended to take a separate catch block. That is try with multiple catch blocks is possible and recommended to use.

If try with multiple catch blocks present then order of catch blocks is very important. It should be from child to parent by mistake if we are taking from parent to child then we will get Compile time error saying.

‘exception xxx has already been caught”

Finally

Finally block:

• It is not recommended to take clean up code ¡n side try block because there is no guarantee for the execution of every statement inside a try.
• It is not recommended to place clean up code inside catch block because if there is no exception then catch block won’t be executed.
• We require some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not handled. Such type of best place ¡s nothing but finally block.
• Hence the main objective of finally block is to maintain cleanup code.

Example:

The speciality of finally block is it will be executed always irrespective of whether the exception raised or not raised and whether handled or not handled

Case-1: If there is no Exception:

Output:
try block executed
Finally block executed

Case-2: If an exception raised but the corresponding catch block matched:

Output:
Try block executed
Catch block executed
Finally block executed

Case-3: If an exception raised but the corresponding catch block not matched:

Output:
Try block executed
Finally block executed
Exception in thread ‘main11 java.lang.ArithmeticException: /by zero at Test.main(Test.java:8)

return Vs finally:

Even though return statement present in try or catch block first finally will be executed and after that only return statement will be considered. i.e finally block dominates return statement.

Output:
try block executed
Finally block executed
If return statement present try, catch and finally blocks then finally block return statement will be considered.

Example:

Output: 999

finally vs System.exit(O):
There is only one situation where the finally block won’t be executed is whenever we are using System.exit(O) method. When ever we are using System.exit(O) then JVM itself will be shutdown, in this case finally block won’t be executed.

i.e., System.exit(O) dominates finally block.

Example:

Output: try

Note:
1. This argument acts as status code. Instead of zero, we can take any integer value

2. Zero means normal termination, non-zero means abnormal termination
3. This status code internally used by JVM, whether it is zero or non-zero there is no change in the result and effect is same wrt program.

Difference between final, finally, and finalize:

final:
• final is the modifier applicable for classes, methods and variables.
• If a class declared as the final then child class creation is not possible.
• If a method declared as the final then overriding of that method is not possible.
• If a variable declared as the final then reassignment is not possible.

finally:
finally is the block always associated with try-catch to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not handled.

finalize:
finalize is a method, always invoked by Garbage Collector just before destroying an object to perform cleanup activities.

Note:
1. finally block meant for cleanup activities related to try block where as finalize() method meant for cleanup activities related to object.
2. To maintain clean up code finally block is recommended over finalize() method because we can’t expect exact behavior of GC.

Control flow in try catch finally:

Case 1:
If there is no exception. 1, 2, 3, 5, 6 normal termination.

Case 2:
If an exception raised at statement 2 and corresponding catch block matched. 1,4,5,6 normal terminations.

Case 3:
If an exception raised at statement 2 and corresponding catch block is not matched. 1,5 abnormal termination.

Case 4:
If an exception raised at statement 4 then it’s always abnormal termination but before the finally block will be executed.

Case 5:
If an exception raised at statement 5 or statement 6 its always abnormal termination.

Various possible combinations of try catch finally:

1. Whenever we are writing try block compulsory we should write either catch or finally. i.e., try without catch or finally is invalid.
2. Whenever we are writing catch block compulsory we should write try. i.e., catch without try is invalid.
3. Whenever we are writing finally block compulsory we should write try. i.e., finally without try is invalid.
4. In try-catch-finally order ¡s important.
5. With in the try-catch -finally blocks we can take try-catch-finally.
i.e., nesting of try-catch-finally is possible.
6. For try-catch-finally blocks curly braces are mandatory.

Throw Statement:

Sometimes we can create Exception object explicitly and we can hand over to the JVM manually by using throw keyword.

The result of following 2 programs is exactly same.

Note:

In general we can use throw keyword for customized exceptions but not for predefined exception.

Example

Case 2:

After throw statement we can’t take any statement directly otherwise we will get compile time error saying unreachable statement.

Example:

Case:3

We can use throw keyword only for Throwable types otherwise we will get compile time error saying incompatible types.

Exception handling keywords summary:

1. try: To maintain risky code.
2. catch: To maintain handling code.
3. finally: To maintain cleanup code.
4. throw: To handover our created exception object to the JVM manually.
5. throws: To delegate responsibility of exception handling to the caller method.

Various possible compile time errors in exception handling:

1. Exception XXX has already been caught.
2. Unreported exception XXX must be caught or declared to be thrown.
3. Exception XXX is never thrown in body of corresponding try statement.
4. Try without catch or finally.
5. Catch without try.
6. Finally without try.
7. Incompatible types.
found:Test
8. Unreachable statement.

Customized Exceptions (User defined Exceptions):

Sometimes we can create our own exception to meet our programming requirements. Such type of exceptions are called customized exceptions
(user defined exceptions).

Example:
1. lnSufficientFundsException
2. TooYoungException
3. TooOldException

Program:

Output:
1)java CustomizedExceptíonDemo 61
Exception in thread “main” TooYoung Exception:
please wait some more time…. u will get best match at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)
2) java Customized Exception Demo 27 You will get match details soon by e-mail

3) java Customized Exception Demo 9 Exception ¡n thread ‘main’ TooOld Exception: u r age already crossed….no chance of getting married at CustomizedExceptionDemo. main(CustomizedExceptionDemo.java:25)

Note:
It is highly recommended to maintain our customized exceptions as unchecked by extending RuntimeException. We can catch any Throwable type including Errors also.

Exception Propagation:

With in a method if an exception raised and if that method doesn’t handle that exception, then Exception object will be propagated to the caller then caller method is responsible to handle that exceptions. This process is called Exception Propagation.

Rethrowing an Exception:

To convert the one exception type to another exception type, we can use rethrowing exception concept.

Output:
RE:NPE


Previous Page


Next Page