Home » Java programming language

Exception Handling with Example in Java

Learn: In this article we will study about the different types of Keywords used for exception handling in java. We will also discuss about their syntax and function with example.
Submitted by Abhishek Jain, on September 02, 2017

In previous article (Basics of Exception handlings in java), we were discussed that, we can implement exception-handling in your program by using the following five keywords:

1) try

The try block contains a series of program statements within which an exception might occur. A try block is always followed by a catch block, which captures the exception occurred at try block.

Syntax:

try{
    // block of code to monitor for errors
}

2) catch()

A catch block is always associated with a try block. It catches the error thrown by try block during program execution. It holds the object of Exception class type.Error that occurs during the program execution generate a specific object which has the information about the errors occurred in the program.

Syntax:

try {
	// block of code to monitor for errors
}
catch (ExceptionType1exOb) {
	// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
	// exception handler for ExceptionType2
}

In the following example code you will see that how the exception handling can be done in java program.

This example reads two integer numbers for the variables a and b. If you enter any other character except number ( 0 - 9 ) then the error is caught by NumberFormatException object. After that ex.getMessage() prints the information about the error occurring causes.

Consider the program:

import java.io.*;

public class ExceptionHandle
{
	public static void main(String[] args) throws Exception
	{
		try{
			int a,b;
			DataInputStream in = new DataInputStream(System.in);
			a = Integer.parseInt(in.readLine());
			b = Integer.parseInt(in.readLine());
		}
		catch(NumberFormatException ex){
			System.out.println(ex.getMessage()
			+ " is not a numeric value.");
		}
		catch(IOException e){
			System.out.println(e.getMessage());
		}
	}
}

3) throw Keyword

The throw statement causes termination of the normal flow of control of the java code and stops the execution of subsequent statements after the throw statement.

Previously, you have only been catching exceptions that are thrown by the JRE system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:

throw ThrowableInstance;

We simply use the throw keyword with an object reference to throw an exception. A single argument is required by the throw statement i.e. a throwable object.

Consider the program:

import java.util.*;

class ExceptionThrow
{ 
	public static void main(String arg[])
	{ 
		try{
			Scanner KB=new Scanner(System.in);
			System.out.print("Enter Percentage:");
			int per=KB.nextInt();
			if(!(per>=0 && per<=100))
			{ 
				throw(new Exception("Invalid Percentage...."+per));
			}
			else
			{
				System.out.println("Valid Percentage...");
			}
		}catch(Exception e){
			System.out.println(e);
		} 
	}
}

4) throws Keyword

The throws clause is used by a method to specify the types of exceptions the methodthrows. The throw keyword indicates the following:

  • The throws keyword in java programming language is applicable to a method to indicatethat the method raises particular type of exception while being processed.
  • The throws keyword in java programming language takes arguments as a list of theobjects of type java.lang.Throwables class.

The general form of throws is given below:

type method-name(parameter-list) throws exception-list
{
    // body of method
}

Here, exception-listis separated by commas (list of the exceptions that a method can throw).

import java.io.*;

class ThrowsKeyword
{ 
	static int division(int x) throws ArithmeticException,NumberFormatException,IOException{ 
		DataInputStream KB=new DataInputStream(System.in);
		System.out.print("Enter Value..");
		int y=Integer.parseInt(KB.readLine());
		int d=x/y;
		return(d);
	}
	public static void main(String arg[])
	{ 
		try{
			int j=division(300);
			System.out.println(j);
		}
		catch(ArithmeticException e){
			System.out.println("Error:"+e.getMessage());
		}
		catch(NumberFormatException e){
			System.out.println("Invalid Input:"+e.getMessage());
		}
		catch(IOException e){
			System.out.println(e.getMessage());
		}
	}
}

5) Finally Block

The finally clause is used to execute the statements that need to be executed whether or not an exception has been thrown.

Use finally clause after the try and catch block to handle an unexpected exception occurred in the try block.

The finally block is executed surely whether the exception is generated or not. Finally block is executed after the execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught.

The syntax of declaring a final type variable is:

try {
	// Normal execution path
}
catch (ExampleExceptionee) {
	// deal with the ExampleException
}
finally {
	// This optional section is executed upon termination 
	//of any of the try or catch blocks above
}



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.