Monday, May 21, 2012

Exception handling in java

Exceptions

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

Checked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception or that may be thrown by using throws clause.

Unchecked exceptions

Unchecked exceptions are RuntimeException and any of its subclasses. however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown.

Exceptions Hierarchy













In java exception handling can be done by using following keywords

try             catch               finally                      throw              throws


try block

The try block encloses the statements that might raise an exception within it and defines the scope of the exception handlers associated with it. A try block must be accompanied by at least one catch block or one finally block.

catch block

The catch block is used as an exception-handler. You enclose the code that you want to monitor inside a try block to handle a run-time error. catch block is an exception handler and handles the type of exception indicated by its argument. The catch block contains code that is executed if and when the exception handler is invoked.

throw

The “throw” keyword is used to manually throw user define exception or custom exception.

throws

When a method is capable of throwing an exception that it does not handle by itself it must declare so with the help of the throws clause.

finally

The finally block also known as resource handler, a try can have only one finally, the finally must be written after the catch block.


ExceptionDemo.java

package com.jsl.core;
import java.util.Scanner;
public class ExceptionDemo {
  public static void main(String[] args) {
    System.out.println("Main method begans");
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
    int res=a/b;
    System.out.println("The a / b is : "+res);
    System.out.println("Main method ends");
  }
}

output:
Main method begans
Enter the a value : 
101
Enter the b value :
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
             at com.jsl.core.ExceptionDemo.main(ExceptionDemo.java:11)

When 101/0 which leads to ArithmeticException, programmer didn't handle the exception then JVM handles exception and program will be terminated.


ExceptionDemo.java

package com.jsl.core;
import java.util.Scanner;
public class ExceptionDemo {
  public static void main(String[] args) {
    
    System.out.println("Main method begans");
    
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
    
    try{
       int res=a/b;
        System.out.println("The a / b is : "+res);
    }catch (Exception e) {
        System.out.println(e);
    }
    System.out.println("Main method ends");
  }
}

output
Main method begans
Enter the a value : 
101
Enter the b value :
0
java.lang.ArithmeticException: / by zero
Main method ends
When 101/0 which leads to ArithmeticException in try block that exception will be thrown to the catch block and handled. Then prints “Main method end” and programm will be terminated.


try with finally:
package com.jsl.core;
import java.util.Scanner;
public class TrywithFinally {
  public static void main(String[] args) { 
    System.out.println("Main method begans");
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
    
    try{
       int res=a/b;
       System.out.println("The a / b is : "+res);
    }finally{
       System.out.println("Finally block");
    }
    System.out.println("Main method ends");
  }
}
OutPut:
Main method begans
Enter the a value : 
101
Enter the b value :
0
Finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
             at com.jsl.core.TrywithFinally.main(TrywithFinally.java:14)
When 101 / 0 then its leads to ArithmaticException there is no catch block to handle then JVM handles that exception before termination it exectues finally block then terminates the program.

try inside return statement and with finally
package com.jsl.core;
import java.util.Scanner;
public class TrywithFinally {
  public static void main(String[] args) {
    System.out.println("Main method begans");
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the a value : ");
    int a=sc.nextInt();
    System.out.println("Enter the b value :");
    int b=sc.nextInt();
   
    try{
       int res=a/b;
       System.out.println("The a / b is : "+res);
       return;
    }catch (Exception e) {
       System.out.println(e);
    }
    finally{
       System.out.println("Finally block");
    }
    System.out.println("End of Main method");
  } 
}

Output
Main method begans
Enter the a value : 
100
Enter the b value :
10
The a / b is : 10
Finally block
Here try block contains return statement before execution of the return statement JVM exectues the finally block then return statement will be executed.


try with the multiple catch blocks


package com.jsl.core;

import java.util.Scanner;

public class TryWithMultipleCatch {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int regno=0;
    String name=null;
    float average=0.0f;
    int total=0;
    try {
      System.out.println("Enter the regno ");
      regno= sc.nextInt();
      System.out.println("Enter the Name ");
      name= sc.next();
      name=name.substring(0,4);
      System.out.println("Enter the no subjects ");
      int no=sc.nextInt();
      int marks[] = new int[no];
      for (int i = 0; i < marks.length; i++) {   
        System.out.println("Enter " + (i + 1) + " Marks"); 
        marks[i] = sc.nextInt();  
      }   
      for(int mark:marks) 
        total=total+mark;     
        average=total/no;      
    } catch (ArrayIndexOutOfBoundsException e) { 
        System.out.println("Please check the array size " + e); 
    }catch (StringIndexOutOfBoundsException e) {  
        System.out.println("Please check the name " + e);   
    } catch (ArithmeticException e) {  
        System.out.println("Please check the total subjects" + e);  
    } catch (Exception e) {  
        System.out.println(e); 
    }   
    System.out.println("The regno is :"+regno);   
    System.out.println("The name "+name); 
    System.out.println("The total marks"+total); 
    System.out.println("The average is :"+average);
  } 
}  

When you write try with multiple exceptions, the super class exception must be last catch block, other wise compilation error.

catch (Exception e) {    
  System.out.println(e);   
}catch (ArrayIndexOutOfBoundsException e) {    
  System.out.println("Please check the array size " + e);   
}catch (StringIndexOutOfBoundsException e) {    
  System.out.println("Please check the name " + e);   
} catch (ArithmeticException e) {    
  System.out.println("Please check the total subjects" + e);   
}   

from java 1.7

try{  -----  ----- 
}catch (ArrayIndexOutOfBoundsException e |StringIndexOutOfBoundsException e) {     System.out.println(e); 
}      


try inside try catch


package com.jsl.core;  
import java.util.Scanner;  
public class TryInsideTry {   
  public static void main(String[] args) {    
    try{     
      System.out.println("Enter the salary ");     
      Scanner sc=new Scanner(System.in);     
      int salary=sc.nextInt();     
      System.out.println("Enter the exp ");     
      int exp=sc.nextInt();     
      int bonus=0;            
      try{       
         int per;        
         if(exp>10){
           System.out.println("Enter percentage");
           per=sc.nextInt();
           bonus=salary*per/100;
         }else{
           System.out.println("Enter percentage");
           per=sc.nextInt();
           bonus=salary*per/0;
         }
      }catch (StringIndexOutOfBoundsException e) {
        System.out.println(e);
      }
      System.out.println("The salary is :"+salary);
      System.out.println("The Total salary is :"+(salary+bonus));
   }catch (Exception e) {
   System.out.println(e);
  }
 }
}


catch inside try catch


package com.jsl.core;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class CatchInsideTryCatch {
 public static void main(String[] args) {
  System.out.println("The main method Starts");
  FileOutputStream fis = null;
  try {
   int a = 100 / 0;
  } catch (Exception e) {
   try {
    fis = new FileOutputStream("lakshman.txt");
    ObjectOutputStream obs = new ObjectOutputStream(fis);
    obs.writeObject(e);
   } catch (Exception e1) {
    System.out.println(e1);
   }

   System.out.println(e);
  }
  System.out.println("The main method ends ");
 }
}


finally with try catch


package com.jsl.core;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConnection {
 public static void main(String[] args) {
  System.out.println("Main method starts");
  Connection con = null;
  Statement st = null;
  ResultSet rs = null;
  try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "java", "java");
   st = con.createStatement();
   rs = st.executeQuery("select empno,ename,sal from emp");
   while (rs.next()) {
    System.out.println(rs.getInt("empno"));
    System.out.println(rs.getString("ename"));
    System.out.println(rs.getDouble("sal"));
   }
  } catch (Exception e) {
   System.out.println("While connecting with database :" + e);
  }
  finally {
   try {
    rs.close();
    st.close();
    con.close();
   } catch (Exception e) {
    System.out.println("While closing : " + e);
   }
  }
  System.out.println("End of the main method");
 }
}

package com.jsl.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ThrowsDemo {
 public static void main(String[] args) throws IOException, NumberFormatException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the item namedd ");
  String item = br.readLine();
  System.out.println("Enter the price");
  double price = Double.parseDouble(br.readLine());

  System.out.println("The message is :" + item);
  System.out.println("The price is :" + price);

 }
}


throw


package com.jsl.core;
public class Product {
 private int pid;
 private String pname;
 private double price;
 public Product(int pid, String pname, double price) {
  if (price & lt; 0)
   throw new IllegalArgumentException("please check the price once it should be - value");
  this.pid = pid;
  this.pname = pname;
  this.price = price;
 }
 @ Override public String toString() {
  return pid + " " + pname + " " + price;
 }
}

package com.jsl.core;
public class Product {
 private int pid;
 private String pname;
 private double price;
 public Product(int pid, String pname, double price) {
  if (price & lt; 0)
   throw new IllegalArgumentException("please check the price once it should be - value");
  this.pid = pid;
  this.pname = pname;
  this.price = price;
 }
 @ Override public String toString() {
  return pid + " " + pname + " " + price;
 }
}

User defined Exceptions:


Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions.


  1. User defined exceptions can be created by extending Excetion class or RuntimeException
  2. User defined Excetion extends Exception then it become checked exception.
  3. User defined Excetion extends RuntimeExcetion it become Unchecked Excetions


Let us see a simple example to learn how to define and make use of user defined exceptions.


InsufficientFundException.java

package com.jsl.excetion.demo;

public class InsufficientFundException extends RuntimeException {

        String message;

        public InsufficientFundException(String message) {

           this.message=message;

        }

public String toString() {

        return "Exception occurred.. " + message;

        }

}

MaxCount.java

package com.jsl.demo;
public class MaxCount extends RuntimeException {

    int count;

    public MaxCount(int count) {

       this.count=count;

    }

    @Override
    public String toString() {

        return " Maximum count reached "+count;

    }

}

BankAccount.java

package com.jsl.demo;

import java.util.Scanner;

import com.jsl.excetion.demo.InsufficientFundException;

public class BankAccount {

          private int balance = 3000;

         volatile int count = 0;

 

         public void withDraw() {

             if (count > 2)

              throw new MaxCount(count);

              System.out.println("Enter the amount to with draw");

              Scanner sc = new Scanner(System.in);


                 int amount = sc.nextInt();

                   if (amount > balance)

                     throw new InsufficientFundException("Sorry you don't sufficient balance ");

                   else {

                     balance = balance - amount;

                     System.out.println("Thank for using your balance is : " + balance);

                       }

                   count++;

             }

}

Main.java

package com.jsl.demo;

import java.util.Scanner;

import com.jsl.excetion.demo.InsufficientFundException;

public class Main {

             public static void main(String[] args) {

                    BankAccount account = new BankAccount();

             for (;;) {

                try {

                  System.out.println("1.Withdraw 2. exit");

                  System.out.println("Enter the choice");

                  int ch = new Scanner(System.in).nextInt();

                  if (ch == 1)

                     account.withDraw();

                     if (ch == 2)

                        System.exit(0);

                   } catch (InsufficientFundException e) {

                        System.out.println(e);

                   } catch (MaxCount e) {

                        System.out.println(e);

                   } catch (Exception e) {

                        System.out.println(e);

                   }

            }

        }

}

No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0...