Exceptions...What do you think? What does it mean? Today, I will answer your questions..This is also a very important topic to be discussed in Java. When we do projects in java, these exceptions always used for many purposes. Let's see..

Exception is an abnormal behavior disrupting the normal flow of any program.. These exceptions are occurred Run Time according to the user reactions and inputs to a program.. These can be managed through validations or otherwise have to create exceptions with a message pass to identify abnormal behaviors.

How this happens?


Why to handle Exceptions?


1. To avoid terminating the program
2. To inform user when there's an abnormal behavior in the program


Basic classification of Exception classes

Checked Exceptions :

These are called Compile Time Exceptions and occurred compile time and have to take measures to handle without ignoring.
Ex: IOException, FileNotFoundException

Unchecked Exceptions :

These ones are occurred when program is executing, called as Run Time Exceptions. They are ignored when a program is compiled.
Ex: ArrayOutOfBounException, ArithmeticException

Some common Exceptions..

ArithmeticException

class Exception{
 public static void main(String args[]){
  int a = 50;
  System.out.println(a/0);
 }
}

ArrayIndexOutOfBoundsException

class Exception{
 public static void main(String args[]){
  int a[] = {1,2,3};  
  System.out.println(a[5]);
 }
}

NullPointerException

class Exception{
 public static void main(String args[]){
  int a[] = null;  
  System.out.println(a.length);
 }
}


Steps to handle an exception :

1. Include a try catch block.
2. Place the code lines that can give errors within the try block.
3. Then start the catch block. Pass an object reference to refer the newly created exception object.
The format is given below.

try {
 // error giving code
} catch(ExceptionClass ObjectRef) {
 // changed code
}

Important Facts : 


Case 1 :

Catch block runs when there's an exception only. Look at this program.. Definitely, try or catch block runs!

class Exception{
 public static void main(String args[]){
  System.out.println("Start Program");
  int x=10,d=2;
  try{
   x=50/d;  // Since d=2 there are no errors. If d = 0 ?
  }catch(ArithmeticException ob){
   System.out.println("This is the catch block");
  }
  System.out.println("End Program");
 }
}

Output :

Case 2 :

After the exception object is created, the remaining coding in the try block will not execute.

class Exception{
 public static void main(String args[]){
  System.out.println("Start Program");
  int x=10,d=0;
  try{
   x=50/d;  // Since d=0 there are errors and runs catch block
  }catch(ArithmeticException ob){
   System.out.println("This is the catch block");
  }
  System.out.println("End Program");
 }
}

Output :


Case 3 : 

If we have created the Exception Object using a incompatible Exception class, there's a problem. Exception handling process is not working. Then JVM hands over the process to the DEH(Default Exception Handler). DEH will terminate the program most of the times.

Case 4 :

We cannot use Object class(most super class of all classes) as an exception class. The Object class does not have throwable qualities.

Case 5 : 

When we run a method chain, we can use try catch block wherever we want.

class Test{
    void testA(){
        System.out.println("Start testA");
        try{
            int d=43/0;
        }catch(ArithmeticException e){}
        System.out.println("End testA");
    }
    void testB(){
        System.out.println("Start testB");
        testA();
        System.out.println("End testB");
    }
    void testC(){
        System.out.println("Start testC");
        testB();
        System.out.println("End testC");
    }
}
class Exception{
    public static void main(String args[]){
        System.out.println("Start main");
        Test c1=new Test();
        c1.testC();
        System.out.println("End main");
    }
}

Output :

Case 6 :

Catch Ladder
We can create multiple catch blocks for a single try block. After reaching a catch block if its object reference is incompatible, then moves into the next catch block. Catch ladder must be continuous and not breakable. If catch ladder is using the Exception classes within the same class hierarchy, the most super class should be included in the last catch block.

class TestException {
    public static void main(String args[]){
        try{
            int x[]=new int[5];
            x[5]=30/0;      // line 1 - influence ArithmeticException
            x[6]=30/6;      // line 2 - influence ArrayIndexOutOfBoundsException
        }
        catch(ArithmeticException e){
            System.out.println("catch block 1");
        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println("catch block 2");
        }
        catch(Exception e){
            System.out.println("catch block 3");
        }
        System.out.println("out of try catch");
    }
}  

Here, output will show catch block 1 since first evaluated line 1 when we run the program. Comment out line 1 and then see the output..Got it? Try catch block 2 will be in the output.

Case 7 :

If the exception is handled for the same code sectiXOn, we can include exception classes within the same catch block using OR operator. 

Finally Block

What is this? Imagine you want to run a finalizing code in your program. If there are exceptions or not that code should run. So, in this kind of situations finally block is used. A try block can have many catch blocks, but only one finally block! So we can open a finally block and place that finalizing code into it.
Example : 
When you handle a file using Java, you have opened a file within your try catch block in the program. This try catch block could not manage the exception occurred. Then JVM gives the process to DEH. The problem is file is not closed here. Therefore you can place the code to close the file, in a finally block!
Look at the below examples..

1. There's no exception and not handled
class TestException {
    public static void main(String args[]){
        try{
            int x[]=new int[5];
            x[2]=30/2;      // influence ArithmeticException
        }
        catch(ArithmeticException e){
            System.out.println("catch block runs");
        }
        finally{System.out.println("This is the Finally block");}
        System.out.println("out of try catch");
    }
}  

Output :

2. There's an exception and not handled
class TestException {
    public static void main(String args[]){
        try{
            int x[]=new int[5];
            x[6]=30/6;      // influence ArrayIndexOutOfBoundsException
        }
        catch(ArithmeticException e){
            System.out.println("catch block runs");
        }
        finally{System.out.println("This is the Finally block");}
        System.out.println("out of try catch");
    }
}  

Output :


3. There's an exception and handled
class TestException {
    public static void main(String args[]){
        try{
            int x[]=new int[5];
            x[2]=30/0;      // influence ArithmeticException
        }
        catch(ArithmeticException e){
            System.out.println("catch block runs");
        }
        finally{System.out.println("This is the Finally block");}
        System.out.println("out of try catch");
    }
}

Output :

You can see, in all these 3 cases, finally block runs..That's the specialty in this block.

Throw Keyword

In java, this throw keyword is used to throw a new exception by force. That exception can be checked or unchecked.. This is an example.

class TestException {
    static void validate(int salary){
        if(salary<30000)
            throw new ArithmeticException("not valid");
        else
            System.out.println("You can apply the loan");
    }
    public static void main(String args[]){
        validate(43000);
        System.out.println("After validation");
    }
}


Throws Keyword

Think that a methods have a possibility to occur an exception..You want to tell this when you declare the function..This is the way to do it.! We can declare s java method adding throws keyword. But whenever you add this code, that method cannot be called directly anywhere. That method must be enclosed to a try catch block.

import java.io.*;
class FileRead{
    public static void readData()throws FileNotFoundException{
        //loading a file
        //read data
    }
}
class TestException{
    public static void main(String args[]){
        System.out.println("Start");
        FileRead c1=new FileRead();
        try{
            c1.readData();
        }catch(FileNotFoundException e){ //IOException e

        }
        System.out.println("End");
    }
}


Exceptions are everywhere...I think now you have got some knowledge from this article. I gave you enough examples to understand this concept. Practice them and give me feedback. I highly appreciate your feedback.
Drop a comment if you have questions.

Bye Guys!




0 Comments