Java Programming
About Lesson

Working mechanism of try…catch…
The risky code (the code which is prone to exception) would be kept inside try block. The catch block follows the try block. If any exception raised inside the try block then it will be thrown outside of try block by creating an object of exception to the matching catch block. The corresponding catch block will handle the exception with the information got from try block.
It is not possible to have a try block without catch or finally block anyone atleast. But finally block is optional. Each try block can have ‘0’ to multiple catch blocks but can have ‘0’ to ‘1’ finally block.

 

Multiple catch blocks
Multiple catch blocks can follow a single try block but only one catch block would be executed to handle the exception raised inside the try block. Hence the catch blocks must be in the order of most specific (Child) to most general (Parent).

//Example code to show multiple catch blocks to be ordered
public static void main(String[] args) {
try
{
System.out.println(10/0);
}
catch(Exception e)
{
System.out.println(“Handling Outer try”);
}
catch(ArithmeticException e)
{
System.out.println(“Handling Outer try”);
}

}

The above code would result a compile time error as “Unreachable code” since the parent Exception class is handling the exception of try block, there is no use of providing another catch block. The error can be corrected by changing the order of catch blocks as child class before and parent class after.

//another example of multiple catch blocks
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[3];
a[5]=30/0;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(“task 2 completed”);
}
catch(ArithmeticException e){
System.out.println(“task1 is completed”);
}
catch(Exception e){
System.out.println(“common task completed”);
}

System.out.println(“rest of the code…”);
}
}

Output:
task1 is completed
rest of the code…

 

Propagation of Exception Handling
The exception raised inside the try block must be handled by a corresponding catch block. In case there is no catch block exists to handle the type of exception raised inside the try block, then the responsibility of handling of exception will be handed over to the caller of the method. In this manner, the handling of exception is propagated towards upper level.
//example code showing how exception handling is propagated towards upper level.
public static void main(String[] args) {
int a = 1;
int b = 0;

try
{
System.out.println(computeDivision(a,b));

}

catch(ArithmeticException ex)
{
System.out.println(ex.getMessage());
}

}

static int divideByZero(int a, int b){

int i = a/b;
return i;
}

static int computeDivision(int a, int b) {

int res =0;

try
{
res = divideByZero(a,b);
}
catch(NumberFormatException ex)
{
System.out.println(“NumberFormatException is occured”);
}
return res;
}

 

The finally block
The finally block is a special block that must be the last block after all catch blocks for a try block. The finally block will always be executed irrespective of the exception raising. Hence, usually clean up code would be placed inside finally block.

Try block without catch but with finally: If you use finally directly after try block, even though the program is terminated abnormally the cleanup code inside finally block will be executed.

//Example code showing how finally is executed always
public static void main(String[] args) {
try{
System.out.println(“code inside try block”);
}
catch(Exception e)
{
System.out.println(“code inside catch block”);
}
finally
{
System.out.println(“code inside finally block”);
}

System.out.println(“rest of the code in main…”);
}
//program describing that finally block is always executed if there is no exception also
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}

//Another program describing finally block when exception occurred but not handled
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}

//finally block when exception occurred and handled
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println(“finally block is always executed”);}
System.out.println(“rest of the code…”);
}
}

 

After checking all the above code segments, we can conclude that the finally block will be executed always in all the below situations:
1. When no exception raised inside try or catch
2. when exception raised inside try or catch, but not handled
3. when exception raised inside try or catch, and handled

But there are some situations where finally block won’t be executed they are System.exit(0) command. The System.exit(0) method will cause shutdown JVM. The ‘0’ inside exit() method is the status code used by JVM to communicate with O/s. Here ‘0’ indicates normal termination while any non-zero value is treated as abnormal termination.
//Example code showing how finally block is skipped
public static void main(String[] args) {
try{
System.out.println(“code inside try block”);
System.exit(0);
}
catch(Exception e)
{
System.out.println(“code inside catch block”);
}
finally
{
System.out.println(“code inside finally block”);
}

System.out.println(“rest of the code in main…”);
}

The code inside finally block won’t be executed even the exception raised inside finally block.
//Example code
public static void main(String[] args) {
try{
System.out.println(“code inside try block”);
}
catch(Exception e)
{
System.out.println(“code inside catch block”);
}
finally
{

System.out.println(10/0);
System.out.println(“Other code in finally block”);
}

System.out.println(“rest of the code in main…”);
}

 

Difference between final, finalise and finally
You may have come to know final, finalise keyword before in this course. Now finally keyword is introduced to you. Let us look the difference between them. The final is keyword as well as non-access specifier of java that can be used with class, method and a variable. A final class cannot be inherited, a final method cannot be over ridden and a final variable cannot change its value. The finalise() method is used to explicitly call the garbage collector by the developer. And we have just understood that finally is a block related to manual exception handling with try…catch.

 

Nested try…catch
Nesting try…catch…finally can be done anywhere that is inside try, inside catch or even inside finally. If the inner catch block cannot handle the exception raised inside a inner try block then it will hand over the responsibility of handling to the outer catch block.

//example code for nested try…catch
public static void main(String[] args) {
try
{
System.out.println(“Outer Try”);
try
{
System.out.println(“Inner Try”);
System.out.println(10/0);
}
catch(ArithmeticException e)
{
System.out.println(“Handling Inner Try block”);
}
System.out.println(“Code after Inner try”);
}
catch(Exception e)
{
System.out.println(“Handling Outer try”);
}
finally
{
System.out.println(“outer finally”);
}

}

It is not possible to have two catch blocks to handle same type of exception but it is possible to have one outer catch block and one inner catch block to handle same type of exception.
//Example code
try
{
try
{
}
catch(X e)
{
}
}
catch(X e)
{
}

Even though the outer catch block can handle the exception raised inside inner try, it is not possible to have an inner try block without catch block. The outer catch takes the responsibility only when the inner catch block failed to handle the exception of inner try.
//example
try
{
try
{
}
}
catch(X e)
{
}
The above code would result in a compile time error.

The curly braces are mandatory for try…catch…finally structure even though they are controlling a zero or single statement. Compiler don’t care whether you have handled code inside catch block but checked whether you inserted catch block after try only.
//example
try
…..
catch(X e)
{
…..
}
finally
{
….
}

You cannot copy content of this page