w3resource

Exceptions in Java programming language

Introduction

A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself or pass it on. Either way, at some point, the exception is caught and processed.

The programs you write can generate many types of potential exceptions, such as when you do the following:

In Java there are three types of loops:

  • You issue a command to read a file from a disk, but the file does not exist there.
  • You attempt to write data to a disk, but the disk is full or unformatted.
  • Your program asks for user input, but the user enters invalid data.
  • The program attempts to divide a value by 0, access an array with a subscript that is too large or calculate a value that is too large for the answer’s variable type.

These errors are called exceptions because, presumably, they are not usual occurrences; they are “exceptional.” The object-oriented techniques to manage such errors comprise the group of methods known as exception handling.

exception in java image-1

Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. Let’s take an example program which will do take two numbers from user and print division result on screen. This might lead to exception condition if the denominator is zero.

Java Code: Go to the editor

import java.util.Scanner;
public class DivideExceptionDemo {
	public static void main(String[] args) {
		//Scanner class is wrapper class of System.in object
		Scanner inputDevice = new Scanner(System.in);
		System.out.print("Please enter first number(numerator): ");
		int numerator = inputDevice.nextInt();
		System.out.print("Please enter second number(denominator): ");
		int denominator = inputDevice.nextInt();
		new DivideExceptionDemo().doDivide(numerator, denominator);
	}
	public void doDivide(int a, int b){
		float result = a/b;
		System.out.println("Division result of "+ a +"/"+b +"= " +result);
	}
}

Output:

Outputs based on user input combinations:

exception in java image-2

Handling Exceptions:

There are two ways of handling the exception, first catch the exception and take corrective action or throws the exception to the calling method which will force the calling method to handle it.

  1. In above program the execution is unexpected and ended in an error condition in case of the denominator is zero. We can avoid this by handling exception using a try-catch block. Let’s update program for exception handling. Here we will write exception prone code inside try block (guarded block) and catch block will follow the try block.

Java Code: Go to the editor

import java.util.Scanner;
public class DivideExceptionHandle {
	public static void main(String[] args) {
		Scanner inputDevice = new Scanner(System.in);
		System.out.print("Please enter first number(numerator): ");
		int numerator = inputDevice.nextInt();
		System.out.print("Please enter second number(denominator): ");
		int denominator = inputDevice.nextInt();		
		new DivideExceptionHandle().doDivide(numerator, denominator);		
	}
	public void doDivide(int a, int b){
		try{
			float result = a/b;
			System.out.println("Division result of "+ a +"/"+b +"= " +result);
		}catch(ArithmeticException e){
			System.out.println("Exception Condition Program is ending ");
		}
	}
}

Output:

Outputs based on user input combination:

exception in java image-3
  1. When a Java method is going to throw an exception, to indicate that as part of the method signature ‘throws‘ keyword should be used followed by the exception. It means that the caller of this method should handle the exception given in the throws clause. There can be multiple exceptions declared to be thrown by a method. If the caller of that method does not handle the exception, then it propagates to one level higher in the method call stack to the previous caller and similarly till it reaches base of the the method call stack which will be the java’s runtime system. For this approach, we use throws keyword in method declaration which will instruct the compiler to handle exception using try-catch block. When we add throws keyword in divide method declaration compile time error will be seen as below,

Java Code: Go to the editor

import java.util.Scanner;
public class DivideExceptionThrows {
	public static void main(String[] args){
		Scanner inputDevice = new Scanner(System.in);
		System.out.print("Please enter first number(numerator): ");
		int numerator = inputDevice.nextInt();
		System.out.print("Please enter second number(denominator): ");
		int denominator = inputDevice.nextInt();		
		try {
			new DivideExceptionThrows().doDivide(numerator, denominator);
		} catch (Exception e) {
			System.out.println("Exception Condition Program is ending ");
		}		
	}
	public void doDivide(int a, int b) throws Exception{
			float result = a/b;
			System.out.println("Division result of "+ a +"/"+b +"= " +result);
	}
}

As you can see either we can surround the code with try-catch block or we can re-throw it to be handled by calling the method. In this case, we are calling a method from the main() method so if we re-throw the exception it would be handled by JVM. Let us update the code and see output based on input combination

Output:

Outputs based on user input combination:

exception in java image-4

Nested Try-catch block:

The try statement can be nested. That is, a try statement can be inside the block of another try.Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted.If no catch statement matches, then the Java runtime system will handle the exception. Below is the syntax of nested try-catch block.

Java Code: Go to the editor

public class NestedTryblockDemo {
	public static void main(String[] args) {
		try{
			//some code	which can throw Exception	
			try {
				//Some code which can throw Arithmatic exception
				try {
					//Some code which can throw number format exception
				}catch(NumberFormatException n){
					//Number format Exception handling
				}
			}catch(ArithmeticException a){
				//ArithmeticException Handling
			}
		}catch(Exception e ){
			//General Exception(SuperClass of all Exception) Handling
		}
	}
}

Use of finally block:

When you have actions you must perform at the end of a try...catch sequence, you can use a finally block. The code within a finally block executes regardless of whether the preceding try block identifies an Exception. Usually, you use a finally block to perform cleanup tasks that must happen whether or not any Exceptions occurred, and whether or not any Exceptions that occurred were caught. In an application where database connection, files are being operated, we need to take of closing those resources in exceptional condition as well as normal condition.

Java Code: Go to the editor

public class TryCatchFinally {
	public void Demo() {
		try {
			// statements to try
		} catch (Exception e) {
			// actions that occur if exception was thrown
		} finally {
			// actions that occur whether catch block executed or not
		}
	}
}

Summary:

We have learned about how exceptions are generated and various ways of handling exceptions. Catching exception or propagating exceptions. We have learned keywords like try, catch, finally, throws and programmatic use of these keywords.

Java Code Editor:

Previous: Java Branching Statements
Next:Checked and unchecked



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-tutorial/exception-in-java.php