1) Introduction to Exception Handling

Exception Handling

The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful features of Java to handle run time error and maintain normal flow of java application.

Exception

An Exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's Instructions.

Types of exceptions

There are two types of exceptions in Java: 1)Checked exceptions 2)Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Why use Exception Handling

Handling the exception is nothing but converting system error generated message into user friendly error message in others word whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user-friendly error message. You can convert system error message into user-friendly error message by using exception handling feature of java.

There are five keywords for Handling the Exception

· Try

· Catch

· Finally

· Throw

· throws

Syntax for handling the exception

Example without Exception Handling:

public class ExceptionHandling {
	public static void main(String[] args) {
		int a=10, b=0;
		b=a/0;
		System.out.println("===Ececuted this Line===");                              
	}
}

As you observe, Abnormally terminate program and give a message like above, this error message is not understandable by user so we convert this error message into user friendly error message, like "denominator not be zero".

Example of Exception Handling:

public class ExceptionHandling {

	public static void main(String[] args) {
		int a=10, b=0;
		try
		{
		b=a/0;
		}
		catch (Exception e)
		{
		System.out.println("Denominator not be zero");
		}            
                          
	}
}

try Block:

Inside try block we write the block of statements which causes executions at run time in other words try block always contains problematic statements.

Important points about try block

· If any exception occurs in try block then CPU controls comes out to the try block and executes appropriate catch block.

· After executing appropriate catch block, even though we use run time statement, CPU control never goes to try block to execute the rest of the statements.

· Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block.

· Each and every try block must contain at least one catch block. But it is highly recommended to write multiple catch blocks for generating multiple user friendly error messages. One try block can contains another try block that is nested or inner try block can be possible.

catch block:

Inside catch block we write the block of statements which will generates user friendly error messages.

Catch block important points

Catch block will execute exception occurs in try block.

You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong.

Multiple catch block:

You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example.

import java.util.*;

public class ExceptionDemo {
	public static void main(String[] args) {
		int a, b, ans = 0;
		Scanner s = new Scanner(System.in);
		System.out.println("Enter any two numbers: ");
		try {
			a = s.nextInt();

			b = s.nextInt();

			ans = a / b;

			System.out.println("Result: " + ans);
		} catch (ArithmeticException ae) {
			System.out.println("Denominator not be zero");
		}

		catch (Exception e) {
			System.out.println("Enter valid number");
		}
	}
}

finally block:

It is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block must be followed by try or catch block.

Why use java finally

Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

Usage of Java finally

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");
		}
		System.out.println("rest of the code");
	}
}

Way to skip finally block

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Hi");
            System.exit(0);
        }
        finally {
            System.out.println("Bye!");
        }
    }
}

In the above code by calling system.exit in try block terminates the JVM due to wich finally block will not be executed.

throw keyword :

/* In this program we are checking the Student age
 * if the student age<12 and weight <40 then our program 
 * should return that the student is not eligible for registration.
 */
public class ThrowExample {
	static void checkEligibilty(int stuage, int stuweight) {
		if (stuage < 12 && stuweight < 40) {
			throw new ArithmeticException("Student is not eligible for registration");
		} else {
			System.out.println("Student Entry is Valid!!");
		}
	}

	public static void main(String args[]) {
		System.out.println("Welcome to the Registration process!!");
		try {
			checkEligibilty(10, 39);
		} catch (Exception e) {
			System.out.println(e);
		}
		System.out.println("Have a nice day..");
	}
}

throws keyword:

As we know that there are two types of exception checked and unchecked. Checked exception (compile time) force you to handle them, if you don’t handle them then the program will not compile. On the other hand unchecked exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for handling checked exceptions. By using throws we can declare multiple exceptions in one go.

What is the need of having throws keyword when you can handle exception using try-catch?

Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or NullPointerException, in this case you can use try-catch as shown below:

public void myMethod()
{
  try {
    // Statements that might throw an exception 
  }
  catch (ArithmeticException e) {
    // Exception handling statements
  }
  catch (NullPointerException e) {
    // Exception handling statements
  }
}

But suppose you have several such methods that can cause exceptions, in that case it would be tedious to write these try-catch for each method. The code will become unnecessary long and will be less-readable.

One way to overcome this problem is by using throws like this: declare the exceptions in the method signature using throws and handle the exceptions where you are calling this method by using try-catch. Another advantage of using this approach is that you will be forced to handle the exception when you call this method, all the exceptions that are declared using throws, must be handled where you are calling this method else you will get compilation error.

public void myMethod() throws ArithmeticException, NullPointerException
{
  // Statements that might throw an exception 
}

public static void main(String args[]) { 
  try {
    myMethod();
  }
  catch (ArithmeticException e) {
    // Exception handling statements
  }
  catch (NullPointerException e) {
    // Exception handling statements
  }
}

Example of throws Keyword

In this example the method myMethod() is throwing two checked exceptions so we have declared these exceptions in the method signature using throws Keyword. If we do not declare these exceptions then the program will throw a compilation error.

import java.io.*;

class ThrowExample {
	void myMethod(int num) throws IOException, ClassNotFoundException {
		if (num == 1)
			throw new IOException("IOException Occurred");
		else
			throw new ClassNotFoundException("ClassNotFoundException");
	}
}

public class Example1 {
	public static void main(String args[]) {
		try {
			ThrowExample obj = new ThrowExample();
			obj.myMethod(1);
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}
}

Last updated