Exception In java


An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Exception hierarchy in java




Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Types of exception

package coreJavaTutorial.ExcepionInJava;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;

public class TypesOfExceptions extends Test1{
      
            static String s1;
           
            //Exception in thread "main" java.lang.ArithmeticException: / by zero
            public static void airthmeticException(){
                        int a = 9/0;
            }
           
            //Exception in thread "main" java.lang.NullPointerException
            public static void nullPointerException(){
                        System.out.println(s1.concat("Test"));
            }
           
            //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
            public static void stackOverFlow(){
                        ArrayList<Integer> array = new ArrayList<Integer>();
                        while(true){
                                    array.add(10);
                        }
            }
            //Exception in thread "main" java.lang.NumberFormatException: For input string: "Test"
            public static void numberFormateException(){
                        String s1 = "Test";
                        int t = Integer.parseInt(s1);
                        int a = 9;
                        Double.parseDouble(s1);
                        Short.parseShort(s1);
                        Long.parseLong(s1);
                        Boolean.parseBoolean(s1);
            }
           
            //Exception in thread "main" java.io.FileNotFoundException: C:/Test.xls (No such file or directory)
            public static void fileNotFoundException() throws FileNotFoundException {
                        FileReader f = new FileReader("C://Test.xls");
            }
           
            //Exception in thread "main" java.lang.ClassNotFoundException: Test124
            public static void classNotFoundException() throws ClassNotFoundException{
                        Class.forName("Test124");
            }
            //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
            public static void arrayIndexOutodbound(){
                        int[] a = new int[5];
                        System.out.println(a[5]);
            }
           
            //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
            public static void outOfMemoryException(){
                        long data[] = new long[1000000000];
            }
           
            //Exception in thread "main" java.lang.ClassCastException: coreJavaTutorial.ExcepionInJava.Test1
            //cannot be cast to coreJavaTutorial.ExcepionInJava.TypesOfExceptions
            public static void classCastException(){
                        Test1 obj = new Test1();
                        System.out.println((TypesOfExceptions)obj);

            }

            //Exception in thread "main" java.lang.NullPointerException
            public static void inputOutputException(){
                        InputStreamReader obj = new InputStreamReader(null);
            }
           
            //Exception in thread "main" java.lang.IllegalStateException: Scanner closed
            public static void illigalStateException(){
                           String s = "Hello World";
                           Scanner scanner = new Scanner(s);
                           System.out.println("" + scanner.nextLine());
                           scanner.close();
                           System.out.println("" + scanner.nextLine());             
            }
            // Checked Exception
            public void test() throws InterruptedException{
                        Thread.sleep(2000);
            }
           
            public static void main(String[] args) throws Exception {
                        /*
                        airthmeticException();
                        nullPointerException();
                        stackOverFlow();
                        numberFormateException();
                        fileNotFoundException();
                        classNotFoundException();
                        arrayIndexOutodbound();
                        outOfMemoryException();
                        classCastException();
                        illigalStateException();
                        */
            }
}


How to handle the exception?


By Try Catch Block:

As we know that when exception comes execution of program will terminate. To avoid that we need to handle the exception.
We need to use try catch block to handle the exception.

First we will see a program has exception and if exception is not handled.

public class Example1 {

            public static void main(String[] args) {
                        int i = 9/0;
                        System.out.println("test is runnign evenafter exception");
            }
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
            at Example1.main(Example1.java:4)
Here from output we can make out that. Once exception comes in program, program execution will terminate.

Example1.main(Example1.java:4) This line says that, we are getting exception in line number 4 which we can see that in eclipse editor.
Once we get this exception, print stamen is not getting executed.

Now we will have handled the exception for the Same program.

public class Example1 {

            public static void main(String[] args) {
                        try {
                                    int i = 9/0;
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        System.out.println("test is runnign evenafter exception");
            }
}

Output: -
java.lang.ArithmeticException: / by zero
test is runnign evenafter exception
            at Example1.main(Example1.java:5)


Here our print statement is getting executed even after exception. Since we are handling the exception by try catch block.


Example:

When we do not handle the exception.

public class Example1 {

            public static void main(String[] args) {
                        String s1 = null;

                        s1.toLowerCase();

                        System.out.println("test is runnign evenafter exception1");
                        System.out.println("test is runnign evenafter exception2");
                        System.out.println("test is runnign evenafter exception3");
            }
}

Output:
Exception in thread "main" java.lang.NullPointerException
            at Example1.main(Example1.java:6)

Once exception will come , rest of the code will not execute.

When we handle the exception

public class Example1 {
 
            public static void main(String[] args) {
                         String s1 = null;
                        try {
                                    s1.toLowerCase();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        System.out.println("test is runnign evenafter exception1");
                        System.out.println("test is runnign evenafter exception2");
                        System.out.println("test is runnign evenafter exception3");
            }
}

Output
java.lang.NullPointerException
            at Example1.main(Example1.java:6)
test is runnign evenafter exception1
test is runnign evenafter exception2
test is runnign evenafter exception3

We can see in the output even we have null pointer exception in code still rest of the code is getting executed. Because we are handling the exception.


Q: Is it possible to catch particular exception by catch block
Answer: - Yes
Q: - Is it possible to write multiple catch block for singe try block.
Answer: - Yes

public class Example2 {

            public static void main(String[] args) {
                        try {
                                    int a = 9 / 0;
                                    int[] array = new int[3];
                                    System.out.println(array[4]);
                        } catch (ArithmeticException e) {
                                    System.out.println("ArithmeticException is gettign called");
                                    e.printStackTrace();
                        } catch (ArrayIndexOutOfBoundsException e) {
                                    System.out.println("ArrayIndexOutOfBoundsException is gettign called");
                                    e.printStackTrace();
                        }
                        System.out.println("Runnign code aftre exception1");
                        System.out.println("Runnign code aftre exception2");
                        System.out.println("Runnign code aftre exception3");
            }
}

·      In This program, when we get ArithmeticException catch block with ArithmeticException will get executed.
·      When We get ArrayIndexOutOfBoundsException catch block with ArrayIndexOutOfBoundsException will get executed.

Output
When we get ArithmeticException
****ArithmeticException is gettign called****
Runnign code aftre exception1
Runnign code aftre exception2
Runnign code aftre exception3
java.lang.ArithmeticException: / by zero
            at Example2.main(Example2.java:6)

When We get ArrayIndexOutOfBoundsException
****ArrayIndexOutOfBoundsException is gettign called****
Runnign code aftre exception1
java.lang.ArrayIndexOutOfBoundsException: 4
Runnign code aftre exception2
Runnign code aftre exception3
            at Example2.main(Example2.java:8)

Q: - Is it possible to write multiple catch block with exception class at the end
Answer: Yes (The benefit is if exception is not cached by child class exception then it will be cached by Exception class)

In this example we will get null pointer exception, in that case catch block with exception class will get executed.

public class Example2 {

            public static void main(String[] args) {
                        try {
                                    int a = 9 / 1;
                                    int[] array = new int[3];
                                    System.out.println(array[2]);
                                    String s1 = null;
                                    s1.toCharArray();
                        } catch (ArithmeticException e) {
                                    System.out.println("****ArithmeticException is gettign called****");
                                    e.printStackTrace();
                        } catch (ArrayIndexOutOfBoundsException e) {
                                    System.out.println("****ArrayIndexOutOfBoundsException is gettign called****");
                                    e.printStackTrace();
                        } catch (Exception e) {
                                    System.out.println("****NullPointerException is gettign called****");
                                    e.printStackTrace();
                        }
                        System.out.println("Runnign code aftre exception1");
                        System.out.println("Runnign code aftre exception2");
                        System.out.println("Runnign code aftre exception3");
            }
}
Output
0
****NullPointerException is gettign called****
java.lang.NullPointerException
Runnign code aftre exception1
Runnign code aftre exception2
Runnign code aftre exception3

            at Example2.main(Example2.java:10)


Q: - is it possible to write exception class as first catch block and then child class exception as last.
Answer: No (When we do show we will get compile time error with message unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception nreachable catch block for ArithmeticException. It is already handled by the catch block for Exception)

public class Example2 {

            public static void main(String[] args) {
                        try {
                                    int a = 9 / 1;
                                    int[] array = new int[3];
                                    System.out.println(array[2]);
                                    String s1 = null;
                                    s1.toCharArray();
                                   
                        } catch (Exception e) {
                                    System.out.println("****NullPointerException is gettign called****");
                                    e.printStackTrace();
                        }
                        catch (ArithmeticException e) {
                                    System.out.println("****ArithmeticException is gettign called****");
                                    e.printStackTrace();
                        } catch (ArrayIndexOutOfBoundsException e) {
                                    System.out.println("****ArrayIndexOutOfBoundsException is gettign called****");
                                    e.printStackTrace();
                        }
                        System.out.println("Runnign code aftre exception1");
                        System.out.println("Runnign code aftre exception2");
                        System.out.println("Runnign code aftre exception3");
            }
}

Throw in Java

When we want throw exception based on condition we can use throw keyword. This will help us to throw exception on run time.

In This example we will throw exception based on age validation

public class ThrowInJava {
           
            public void validateAge(int age){
                        if(age<18){
                                    throw new ArithmeticException("person age is not valid for voting");
                        }
                        else{
                                    System.out.println("person is valid for voting");
                        }
            }
           
            public static void main(String[] args) {
                        ThrowInJava obj = new ThrowInJava();
                        obj.validateAge(17);
            }

}

output:
Exception in thread "main" java.lang.ArithmeticException: person age is not valid for voting
            at ThrowInJava.validateAge(ThrowInJava.java:6)
            at ThrowInJava.main(ThrowInJava.java:15)

When method throw exception, it’s up to caller how he wants to handle that. Why calling this method he can handle by try catch block?


public class ThrowInJava {
           
            public void validateAge(int age){
                        if(age<18){
                                    throw new ArithmeticException("person age is not valid for voting");
                        }
                        else{
                                    System.out.println("person is valid for voting");
                        }
            }
           
// In this method we are calling validate Age method and handling through try catch block
            public void callvalidateAge(int age){
                        try {
                                    validateAge(age);
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }          
            }
           
            public static void main(String[] args) {
                        ThrowInJava obj = new ThrowInJava();
                        obj.validateAge(17);
            }


}


Throws Keyword in Java

The Throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.

public class ThrowsInJava {
        
         public void validateAge(int age) throws ArithmeticException{
                  if(age<18){
                           throw new ArithmeticException("person age is not valid for voting");
                  }
                  else{
                           System.out.println("person is valid for voting");
                  }
         }
}

The above example it will throws ArithmeticException so that whenever we call this method from any class, it will force us to handle the exception

Example:

public class ThrowsInJava {
        
         public void validateAge(int age) throws ArrayIndexOutOfBoundsException{
                  int[] a = new int[4];
         }
}


The above example it will throws ArrayIndexOutOfBoundsException so that whenever we call this method from any class, it will force us to handle the exception

The throw keyword is used to throw an exception from within a method. When a throw statement is encountered and executed, execution of the current method is stopped and returned to the caller.

Whereas the throws keyword is used to declare that a method may throw one or some exceptions. The caller has to catch the exceptions (catching is optional if the exceptions are of type unchecked exceptions

import java.io.File;
import java.io.FileNotFoundException;

public class ThrowInJava {
           
            void deleteFile(File file) throws FileNotFoundException {
                        if (!file.exists()) {
                                    throw new FileNotFoundException();
                        }
                        file.delete();
            }
}

Finally block in Java:

Java Finally blocked will always get executed whether we have handled the exception or not.

In This example we are not handling ArithmeticException in catch block, still finally block will get executed.

Finally blocked is used to execute important code like closing DB connection, closing file connection.

public class ThrowInJava {
           
public static void main(String[] args) {
            try {
                        int i = 9/0;
            } catch (NullPointerException e) {
                        e.printStackTrace();
            }
            finally{
                        System.out.println(" I am finally");
            }
}
}

Output
java.lang.ArithmeticException: / by zero
 I am finally
            at ThrowInJava.main(ThrowInJava.java:6)

Q: Is finally blocked will get executed, if we have return statement in try block.
Answer: - Yes (In general Return statement will be the last line of code after that compile will be returned from method or block).

public class ThrowInJava {
           
public static void main(String[] args) {
            try {
                        int i = 9/10;
                        return;
            } catch (NullPointerException e) {
                        System.out.println("I am in catch block");
            }
            finally{
                        System.out.println(" I am finally");
            }
}
}
 Output:
I am finally

In above example even though we have return statement still finally is getting executed.








Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Exceptions in Java. An exception is an unwanted or unexpected event that occurs while a program i is running.e at runtime, that interferes with the normal flow of instructions of the program. Error: an error indicates a serious problem that a reasonable application should not try to catch.
    This is very good information for the beginners. The entire article is easy to read and understand. Thank you for writing such a valuable content for us.
    https://www.exltech.in/java-training.html

    ReplyDelete
  3. Good Post! Thank you so much for sharing the nice post, it was so good to read and useful to improve
    Java Training in Electronic City

    ReplyDelete

Post a Comment

Popular posts from this blog

CollectionFramework-Part-2 In Java

OOPs concepts In Java