Adds

Exception Handling in Java

Java Exception Handling Tutorial List :

What is an exception ?

An exception is a condition that prevents your program from further executing along the current path.An Exception can interrupts the normal flow of the program. When an exception occurs normal program processing gets terminated. Java provides an object oriented way to handle exception scenarios, known as Java Exception Handling.

Java Exception Handling Overview

An exception is an abnormal condition that arises in a program execution at run time. In other words , an exception is a run-time error. when exceptional condition arises, an object representing that exception is created and thrown in the method that causes this error.

Exceptions can be generated by the java run-time system or they can be manually generated by your java code .system generated exception are automatically thrown by the java run time system .To manually throw an exception, we need to use the keyword throw.

Exceptional handling is a mechanism of converting system error messages into user friendly messages.

Errors

Errors are the problems which we can't handle.Errors are of two types.

  • Compile Time Error
  • Run Time Error

Compile Time Error

Compile time errors are those which are occurring because of poor understanding of the language.

Run Time Error

Run time errors are those which can occur in a correct program when the user inputs invalid data.The run time errors must be converted to user friendly message by the JAVA programmer by using the concept of exceptional handling.


Exception Hierarchy


Java Exception


Types of Exception

There are two types of exceptions: checked exceptions and unchecked exceptions.

Checked Exception(Compile Time Exception)

A checked exception is one which always deals with compile time errors.Checked exceptions are checked at compile-time.If a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise compilation error will occur in the program.

Checked exception can be predicted by the programmer.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.

Lets consider the example given below.

package com.jwt.java;

import java.io.FileInputStream;

public class CompileTime {
	public static void main(String args[]) {
		FileInputStream fis = null;
		
		 //This constructor FileInputStream(File filename) throws
		 //FileNotFoundException which is a checked exception
		fis = new FileInputStream("D:/file.txt");
		int n;

		
		 //Method read() of FileInputStream class also throws a checked
		 //exception: IOException
		while ((n = fis.read()) != -1) {
			System.out.print((char)n);
		}

		 //The method close() closes the file input stream It throws IOException
		fis.close();
	}
}

In the above example we are reading the file file.txt and displaying its content on the console.There are three places where an checked exception is thrown in this program as mentioned in the comments.

  • FileInputStream which is used for specifying the file path and name, throws FileNotFoundException.
  • The read() method which reads the file contents throws IOException.
  • close() method which closes the file input stream also throws IOException.

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	Unhandled exception type FileNotFoundException
	Unhandled exception type IOException
	Unhandled exception type IOException

	at com.jwt.java.CompileTime.main(CompileTime.java:12)

The reason for this exception is compile time exceptions gets checked during compile time. Since we didn’t handled/declared the exceptions, our program gave the compilation error.There are two ways to avoid this error.


1. Declare the exception using throws keyword.

package com.jwt.java;

import java.io.FileInputStream;
import java.io.IOException;

public class CompileTime {
	public static void main(String args[])throws IOException {
		FileInputStream fis = null;
		
		 //This constructor FileInputStream(File filename) throws
		 //FileNotFoundException which is a checked exception	 
		fis = new FileInputStream("D:/file.txt");
		int n;

		
		 //Method read() of FileInputStream class also throws a checked
		 //exception: IOException
		while ((n = fis.read()) != -1) {
			System.out.print((char)n);
		}
	
		//The method close() closes the file input stream It throws IOException
		fis.close();
	}
}


Handling exception using throws keyword is fine but it is not a best exception handling practice. You should give meaningful message for each exception type so that it would be easy for someone to understand the error. You should prefer try/catch block to handle exceptional scenarios.


2 . Handle Exception using try-catch blocks.

package com.jwt.java;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CompileTime {
	public static void main(String args[]) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("D:/file.txt");
		} catch (FileNotFoundException fe) {
			System.out.println("The specified file not found "
					+ "at the given path");
		}
		int k;
		try {
			while ((k = fis.read()) != -1) {
				System.out.print((char) k);
			}
			fis.close();
		} catch (IOException ioe) {
			System.out.println("I/O error occurred: " + ioe);
		}
	}
}

UnChecked Exception(RunTimeException)

Unchecked exceptions are not checked at compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a compilation error. Unchecked exceptions or RunTimeException are those which are always deals with programmatic run time errors such as ArithmeticException, NumberFormatException, ArrayIndexOutOfBoundsExcept etc.All Unchecked exceptions are direct sub classes of RuntimeException class.


Lets understand this with an example:

class Example {  
   public static void main(String args[])
   {
	int num1=10;
	int num2=0;
	int result=num1/num2;
	System.out.println(result);
   }
}

Above code will compile successfully however when you will run, it would throw ArithmeticException because we are dividing the no by zero. That clearly shows that unchecked exceptions are not checked at compile-time, they are being checked at runtime. Lets see another example.

class Example {  
   public static void main(String args[])
   {
	int arr[] ={1,2,3,4,5};
	System.out.println(arr[9]);
   }
}

Above code will compile successfully since ArrayIndexOutOfBoundsException is also an unchecked exception. Note: It doesn’t mean that compiler is not checking these exceptions so we shouldn’t handle them. In fact we should handle them more carefully. For e.g. In the above example there should be a exception message to user that they are trying to display a value which doesn’t exist in array so that user would be able to correct the issue.

class Example {  
	public static void main(String args[])
	{
		try{
		int arr[] ={1,2,3,4,5};
		System.out.println(arr[9]);
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("The specified index does not exist " +
					"in array. Please correct the error.");
		}
	}
}

Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception Scenario

Below is some scenarios where unchecked exceptions can occur in java programming.

1 . ArithmeticException

If we divide any number by zero, then ArithmeticException will occur.

int a=50/0;//ArithmeticException  

2 . NullPointerException

String s=null;  
System.out.println(s.length());//NullPointerException  

3 . ArrayIndexOutOfBoundsException

If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below

int a[]=new int[5];  
a[10]=50; //ArrayIndexOutOfBoundsException    

Next Topic :-Java Exception Handling Keywords




comments powered by Disqus