Java – Exception Handling

Java – Exception Handling

Stuff happens. The file isn’t there. The server or database is down. No matter how good a programmer you are, you can’t control everything. Things can go wrong, very wrong. When you write a risky method, you need to handle the bad things that might happens. But how do you know when a method is risky and when do you put the code to handle the exception situation?
Basically, an Exception is runtime error. All exceptions occurs only at runtime but some exceptions are detected at compile time and other some others at runtime. The exception that are checked at compilation time by Java compiler are called ‘checked exceptions‘ while the exceptions that are checked at runtime by the JVM are called ‘unchecked exceptions‘.

Exception Hierarchy

Exception Hiearrchy

Throwable is a class that represents all errors and exceptions which may occur in Java. While Exception is the superclass of all exception in java.

Let’s have an example which shows why Exception Handling is important.

public class ExceptionDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a = 10;
		int b = 0;

		// divide a to b and assign result into new variable
		int c = a/b;
		System.out.println("Integer C: "+c);
		System.out.println("\nContinue to further execution....");
	}

}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.c2s.corejava.ExceptionDemo.main(ExceptionDemo.java:11)

The above given example clearly shows us that why it is important to handle exceptions.

Exception Handling

1). The programmer should observe the statement in their program to check if there is possibility of exception. Such statement should be enclosed within a try block.

try{
  //statements;
}

The importance of try block is that even if some exception occurs inside it, the program will not be terminated. When JVM knows that there is an exception, it stores the exception details in an exception stack and jumps into a catch block.

2). The catch block helps programmer to display the exception details to the user. This helps programmer to understand that there is some error in the program and also displays an user-friendly error message.

catch(Exception e) {
   //statements;
}

3). Lastly, the programmer should perform clean operation like closing the file, database connection, terminating thread etc. The programmer write this code in the finally block.

finally{
  //statements;
}

 

Lets revisit our previous example with Exception Handling –

package com.c2s.corejava;

public class ExceptionDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a = 10;
		int b = 0;
		int c = 0;
		// divide a to b and assign result into new variable
		try{
		 c = a/b;
		}catch(ArithmeticException ae){
			System.out.println("A number can't be divisible by zero,please divide by correct value- " + ae);
		}finally{
			System.out.println("Close the connections if there is any!");
		}
		
		System.out.println("Integer C: "+c);
		System.out.println("\nContinue to further execution...");
	}
}

Output:

A number can't be divisible by zero,please divide by correct value- java.lang.ArithmeticException: / by zero
Close the connections if there is any!
Integer C: 0

Continue to further execution…

 

Example – Multiple Exception Handling

public class MultipleExHandling {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Start...");
		int a = 10;
		int b = 0;
		int c = 0;
		int d[] = {10,20,30};

		try{
			c = a/b;	
			d[40] = 40;	
		}catch(ArithmeticException ae){
			System.out.println("Inside Arithmetic Exception catch");
			System.out.println("A number can't be divisible by zero,please divide by correct value- " + ae);
		}catch(ArrayIndexOutOfBoundsException aie){
			System.out.println("Inside Array Index Out Of Bounds Exception catch");
			System.out.println("Please enter the value within the range- " + aie);
		}finally{
			System.out.println("Inside finally");
			System.out.println("Close the connections if there is any!");
		}
		System.out.println("Integer C: "+c);
		System.out.println("Array d values-");
		for(int i=0; i<d.length;i++){
			System.out.println(d[i]);
		}
		System.out.println("\nContinue to further execution...");

	}

}

Output:

Start...
Inside Arithmetic Exception catch
A number can't be divisible by zero,please divide by correct value- java.lang.ArithmeticException: / by zero
Inside finally
Close the connections if there is any!
Integer C: 0
Array d values-
10
20
30

Continue to further execution...

 

Now correct the ArithmeticException and again execute the program –

package com.c2s.corejava;

public class MultipleExHandling {

	public static void main(String[] args) {
		System.out.println("Start...");
		int a = 10;
		int b = 2;
		int c = 0;
		int d[] = {10,20,30};

		try{
			c = a/b;	
			d[40] = 40;	
		}catch(ArithmeticException ae){
			System.out.println("Inside Arithmetic Exception catch");
			System.out.println("A number can't be divisible by zero,please divide by correct value- " + ae);
		}catch(ArrayIndexOutOfBoundsException aie){
			System.out.println("Inside Array Index Out Of Bounds Exception catch");
			System.out.println("Please enter the value within the range- " + aie);
		}finally{
			System.out.println("Inside finally");
			System.out.println("Close the connections if there is any!");
		}
		System.out.println("Integer C: "+c);
		System.out.println("Array d values-");
		for(int i=0; i<d.length;i++){
			System.out.println(d[i]);
		}
		System.out.println("\nContinue to further execution...");

	}

}

Output:

Start...
Inside Array Index Out Of Bounds Exception catch
Please enter the value within the range- java.lang.ArrayIndexOutOfBoundsException: 40
Inside finally
Close the connections if there is any!
Integer C: 5
Array d values-
10
20
30

Continue to further execution...

Throws Clause

Even if the programmer is not handling runtime exception, the Java compiler will not give any error related to runtime exception. But programmer should handle checked exception. So in this case, if programmer does not want to handle the checked exception, he/she should throw them out using ‘throws’ clause. Otherwise there will be an error flagged by Java compiler which can be easily seen in Eclipse or other related IDE.

package com.c2s.corejava;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ThrowsDemo {
	private String name;
	public static void main(String[] args) throws IOException {
		ThrowsDemo obj = new ThrowsDemo();
		obj.acceptName();
		obj.display();
		
	}
	
	void acceptName() throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter name: ");
		name = br.readLine();
	}
	
	void display(){
		System.out.println("Name: "+name);
	}

}

Output:

Enter name: 
Code2Succeed
Name: Code2Succeed

 

Programmer can also define their own exception. Click here to know more.

Stay tuned for more updates !

 

Leave a Reply

Your email address will not be published. Required fields are marked *