W3Resource: "Exceptions in Java"

This article article illustrates the Java flow to handle an exception. Java uses 'try' and 'catch' blocks for the code that handles the exception, and a 'throw' keyword used in the method where the exception occurs. There are 4 sections to the reading, each after the first accessed by clicking <next>. Be sure to read each.


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 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:

  1. import java.util.Scanner;  
  2. public class DivideExceptionDemo {  
  3.     public static void main(String[] args) {  
  4.         //Scanner class is wrapper class of System.in object  
  5.         Scanner inputDevice = new Scanner(System.in);  
  6.         System.out.print("Please enter first number(numerator): ");  
  7.         int numerator = inputDevice.nextInt();  
  8.         System.out.print("Please enter second number(denominator): ");  
  9.         int denominator = inputDevice.nextInt();  
  10.         new DivideExceptionDemo().doDivide(numerator, denominator);  
  11.     }  
  12.     public void doDivide(int a, int b){  
  13.         float result = a/b;  
  14.         System.out.println("Division result of "+ a +"/"+b +"= " +result);  
  15.     }  
  16. }  


Outputs based on user input combinations:

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:

  1. import java.util.Scanner;  
  2. public class DivideExceptionHandle {  
  3.     public static void main(String[] args) {  
  4.         Scanner inputDevice = new Scanner(System.in);  
  5.         System.out.print("Please enter first number(numerator): ");  
  6.         int numerator = inputDevice.nextInt();  
  7.         System.out.print("Please enter second number(denominator): ");  
  8.         int denominator = inputDevice.nextInt();          
  9.         new DivideExceptionHandle().doDivide(numerator, denominator);         
  10.     }  
  11.     public void doDivide(int a, int b){  
  12.         try{  
  13.             float result = a/b;  
  14.             System.out.println("Division result of "+ a +"/"+b +"= " +result);  
  15.         }catch(ArithmeticException e){  
  16.             System.out.println("Exception Condition Program is ending ");  
  17.         }  
  18.     }  
  19. }  


Outputs based on user input combination:

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:

  1. import java.util.Scanner;  
  2. public class DivideExceptionThrows {  
  3.     public static void main(String[] args){  
  4.         Scanner inputDevice = new Scanner(System.in);  
  5.         System.out.print("Please enter first number(numerator): ");  
  6.         int numerator = inputDevice.nextInt();  
  7.         System.out.print("Please enter second number(denominator): ");  
  8.         int denominator = inputDevice.nextInt();          
  9.         try {  
  10.             new DivideExceptionThrows().doDivide(numerator, denominator);  
  11.         } catch (Exception e) {  
  12.             System.out.println("Exception Condition Program is ending ");  
  13.         }         
  14.     }  
  15.     public void doDivide(int a, int b) throws Exception{  
  16.             float result = a/b;  
  17.             System.out.println("Division result of "+ a +"/"+b +"= " +result);  
  18.     }  
  19. }  

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


Outputs based on user input combination:

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: 

  1. public class NestedTryblockDemo {  
  2.     public static void main(String[] args) {  
  3.         try{  
  4.             //some code which can throw Exception     
  5.             try {  
  6.                 //Some code which can throw Arithmatic exception  
  7.                 try {  
  8.                     //Some code which can throw number format exception  
  9.                 }catch(NumberFormatException n){  
  10.                     //Number format Exception handling  
  11.                 }  
  12.             }catch(ArithmeticException a){  
  13.                 //ArithmeticException Handling  
  14.             }  
  15.         }catch(Exception e ){  
  16.             //General Exception(SuperClass of all Exception) Handling  
  17.         }  
  18.     }  
  19. }  

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: 

  1. public class TryCatchFinally {  
  2.     public void Demo() {  
  3.         try {  
  4.             // statements to try  
  5.         } catch (Exception e) {  
  6.             // actions that occur if exception was thrown  
  7.         } finally {  
  8.             // actions that occur whether catch block executed or not  
  9.         }  
  10.     }  
  11. }  

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.

Source: http://www.w3resource.com/java-tutorial/exception-in-java.php
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.


Last modified: Tuesday, October 15, 2019, 11:59 AM