Handling Exceptions (Part 2)

Pre-requisites : File Reading using scanner , Arrays

Exceptions 

Exceptions are warnings or error messages by the Java compiler which can be easily handled. This functionality is called as Exception Handling. Whenever an exception is occurred , the flow of the program is disrupted and execution of code below it remains unexecuted. 



There are 2 types of exceptions:  

1. Checked / Compile-time Exceptions 

An exception which is checked / notified at compile time is called as Checked OR Compile-time Exceptions. These exceptions cannot be ignored and must be handled.

Eg:- Whenever we use File Class to read a file , if at our mentioned directory the file is not present at that instant , we get FileNotFoundException . 
 import java.io.File;  
 import java.util.Scanner;  
   
 public class MyClass {  
     public static void main(String[] args) {  
         String fileLoc = "C://user//desktop//example.txt";  
         File file = new File(fileLoc);  
   
         // Unhandled exception at this line of type FileNotFoundException  
         Scanner scan = new Scanner(file);  
     }  
 }  
If you try to compile the above program , you will get error message for unhandled FileNotFoundException.




2. Unchecked / Run-time Exceptions 

An exception which is checked / notified at run time is called as Unchecked OR Run-time Exceptions. These exceptions are mainly due to human errors or logic errors.

Eg:- When we construct an array of say 5 elements and the user tries to access its 6th elements i.e at index 5 , the compiler will throw an ArrayOutOfBoundsException.
 public class MyClass {  
     public static void main(String[] args) {  

         // array of 5 elements  
         int[] arr = { 2, 3, 1, 5, 4 };  
   
         // access its 6th element i.e index 5  
         System.out.println(arr[5]);  
     }  
 }  



Exception Hierarchy

All exceptions are types of java.lang Exeption class. The hierarchy is shown below:


Errors:- Errors are unlike exceptions for which they are going to arrive and are beyond the control of the programmer. These are ignored in many cases as one can rarely do anything about an error.



Exception Handling

There are mainly two ways to handle an exception :

1. Using throws statement

We can handle exceptions by writing throws statement. Here I will show you how to catch an FileNotFoundException using throws statement , but you can catch any exception using throws statement. 

Sometimes while using File Class , we get IOException. IOException is thrown by the compiler when the Java compiler is unable to perform Input / output operations on the file.
  import java.io.File;   
  import java.io.FileNotFoundException;   
  import java.util.Scanner;   
     
  public class MyClass {   
    public static void main(String[] args) throws FileNotFoundException {   
       File file = new File("C:\\Users\\Desktop\\example.txt");   
       Scanner scan = new Scanner(file);   
          
       // using while loop to read lines from file   
       while (scan.hasNext()) {     
         System.out.println(scan.nextLine());   
       }   
       scan.close();   
    }   
  }  
Output:-
 Hello I am a Text File.  
 This is my 2nd line.  
 This is my 3rd line.  
 Thank You.  

When the compiler is unable to find file OR you change the file location : 
 Exception in thread "main" java.io.FileNotFoundException: C:\Users\bharg\Desktop\examplee.txt (The system cannot find the file specified)  





2. Using try-catch block

Another way to handle exceptions is by using a try-catch block. Here I will use the same program above so that to understood both cases in a much clearer way.

Here also we have to catch FileNotFoundException / IOException using try-catch block.

Another benefit of try-catch block is that when an exception is occurred you can display your own error message so as to make the user understand about problem occurred. Also it is more feasible than throws statement.
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.util.Scanner;  
   
 public class MyClass {  
     public static void main(String[] args) {  
         String fileLoc = "C://Users//Desktop//example.txt";  
   
         File file = new File(fileLoc);  
   
         // using try-catch block  
         try {  
             Scanner scan = new Scanner(file);  
             while (scan.hasNext()) {  
                 System.out.println(scan.nextLine());  
             }  
             scan.close();  
         } catch (FileNotFoundException e) {  
             System.out.println("Unable to find file: " + file.toString());  
         }  
   
     }  
 }  
Output:-
 Hello I am a Text File.  
 This is my 2nd line.  
 This is my 3rd line.  
 Thank You.  

The code written inside the try block is suspicious of throwing exceptions. It is normally executed until an exception is found , once found it directly jumps out of the try block. When an exception is found anything written after it remains unexecuted.

The catch block helps in catching the exceptions which the try block is likely to throw.  


When the compiler is unable to find file OR you change the file location : 
Unable to find file: C:\Users\Desktop\examplee.txt 



3. Using finally block

Any code written inside finally block gets executed no matter the exception is thrown or not.
Using the same program above to understand the concept bit more clearly.
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.util.Scanner;  
   
 public class MyClass {  
     public static void main(String[] args) {  
         String fileLoc = "C://Users//Desktop//examplee.txt";  
   
         File file = new File(fileLoc);  
   
         // using try-catch block  
         try {  
             Scanner scan = new Scanner(file);  
             while (scan.hasNext()) {  
                 System.out.println(scan.nextLine());  
             }  
             scan.close();  
         } catch (FileNotFoundException e) {  
             System.out.println("Unable to find file: " + file.toString());  
         }  
   
         // finally block gets executed independent of exceptions  
         finally {  
             System.out.println("Text file provided by Java Monk.");  
         }  
     }  
 }  
Output:-
 Hello I am a Text File.  
 This is my 2nd line.  
 This is my 3rd line.  
 Thank You.  
 Text file provided by Java Monk.  


When the compiler is unable to find file OR you change the file location : 
 Unable to find file: C:\Users\Desktop\examplee.txt 
 Text file provided by Java Monk.  



< Previous Next >