UNit-3 : Exception Handling

 An exception is a runtime error, which will distrupts the normal flow of application.


 Checked exceptions

checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions.

1. ClassNotFoundException: This exception is thrown when the JVM tries to load a class, which is not present in the classpath.

   Class.forName("oracle.jdbc.driver.OracleDriver");

 

2. FileNotFoundException: This exception is thrown when the program tries to access a file that does not exist or does not open. This error occurs mainly in file handling programs.

File file = new File("E:// file.txt");

FileReader fr = new FileReader(file);

 

3.IOException: This exception is thrown when the input-output operation in a program fails or is interrupted during the program’s execution.

 

4.InterruptedException: This exception occurs whenever a thread is processing, sleeping or waiting in a multithreading program and it is interrupted.

Thread t = new Thread();

    t.sleep(10000);

 

Unchecked exceptions:

An Unchecked exception is an exception that occurs at the time of execution, these are also called as Runtime Exceptions.

1.ArithmeticException: This exception occurs when a program encounters an error in arithmetic operations such as divide by zero.

class Test{

public static void main(String[] args){

System.out.println(120/0);

}

}

 2.ArrayIndexOutOfBoundsException: This exception is thrown when an array is accessed using an illegal index. The index used is either more than the size of the array or is a negative index. Java doesn’t support negative indexing.

class Test{

public static void main(String[] args){

int[] a = {10,20,30};

System.out.println(a[50]);

}

}

 3.NullPointerException: This exception is raised when a null object is referred to in a program. NullPointerException is the most important and common exception in Java.

class Test{

public static void main(String[] args) {

String s = null;

System.out.println(s.length()); } }

 

4.NumberFormatException: This exception is thrown when a method could not convert a string into a numeric format.

class Test{

public static void main(String[] args){

String a = "abc";

int num=Integer.parseInt(a);

}

}

5. StringIndexOutOfBoundsException: This exception is thrown by the string class, and it indicates that the index is beyond the size of the string object or is negative.

 class Test{

public static void main(String[] args){

String a = "JAVA";

char c = a.charAt(6);

System.out.println(c);

}

}

 

Exception-Handling

 “Exception handling is the mechanism to handle run time errors, so that the normal flow of application can be maintained.”

Exception Handling is managed by using 5 Keywords.

1. try      

2. catch     

3. throw      

4. throws     

5. finally

 

1) try – Defines a block to monitor for exceptions.

2) catch – Handles the exception thrown in the try block.

3) finally – Defines a block that always executes (used for cleanup).

4) throw – Used to manually throw an exception.

5) throws – Declares exceptions a method might throw.

//explain the exception handling mechanism with example or

Explain 5 keywords with example

 class ExceptionDemo {

    public static void main(String[] args) {

        try {

            check(1); // may throw exceptions

        }

catch (Exception e) {

            System.out.println("Caught: " + e);

        }

finally {

            System.out.println("Finally block always runs.");

        }

    }

static void check(int i) throws ArithmeticException, ArrayIndexOutOfBoundsException {

           if (i == 0)

            throw new ArithmeticException("Divide by zero");

        else

            throw new ArrayIndexOutOfBoundsException("Index out of bounds");

    }

}

 

Write a java program for Creating own exception / user defined exception/customized exception

 Java allows us to create our own exception class to provide own exception implementation.

Eg1: class NegativeAgeException extends Exception

        {  

                 NegativeAgeException(String s)

                      {  

                           super(s);  

                        }   

public  String toString()

{

return "Age Exception";

}

           }  

 

class ExcepDemo2

     {  

   static void validate(int age) throws NegativeAgeException

   {  

        if(age<0)  

           throw new NegativeAgeException("  not valid  "+age);  

        else  

            System.out.println("  welcome to the world  " +age);  

     }  

  public static void main(String args[])

{  

          try{  

               validate(23);  

validate(17)

validate(-12);

validate(25);  // Not Executed

              }

                    catch(Exception m)

                        {

System.out.println("Exception occured: No Negative Age");

System.out.println("--- " + m + "---");

                         }  

                     finally {

 System.out.println("Finally block executed");

 }

                   System.out.println("rest of the code...");  

                }  

          }  

 Eg2:

import java.util.*;

class InsufficientFundsException extends Exception

{

InsufficientFundsException(String s)

{

super(s);

}

}

class Test

{

public static void main(String[] args)

{

Scanner obj = new Scanner(System.in);

double balance = 10000.00;

double amt = obj.nextDouble();

try

{

if(amt<=balance)

{

     System.out.println("pls take the cash");

     balance = balance - amt;

}

else

throw new InsufficientFundsException("No Balance in your account");

}

catch (InsufficientFundsException e)

{

System.out.println(e.getMessage());

}

finally

{

System.out.println("Updated Balance:"+balance);

System.out.println("Pls take your card");

}

}

}

Comments

Popular posts from this blog

Java Programming Preparation

Java Programming Syllabus

Unit-I (Introduction to Java)