February 5, 2011

Exception Handling in Java

Java's Exception-handling mechanism cleanly separates the exception-generating code from the exception-handling code.


import java.io.*;
import java.sql.*;

public class Test {

   public void m1() throws ClassNotFoundException {

      try {
  
         FileReader f = new FileReader("test.txt");
                   // throws FileNotFoundException

         Connection c = DriverManager.getConnection("test");
                   // throws SQLException

         Class.forName(info.icontraining.Test);
                   // throws ClassNotFoundException

      } catch (FileNotFoundException e) {
         System.err.println(e.getMessage());
      } catch (SQLException e) {
         System.err.println(e.getMessage()); 
      } catch (Exception e) {
         System.err.println("catch all other exceptions");
         System.err.println(e.getMessage());
      } finally {
         System.out.println("In the finally block");
      }
   }

   public static void main(String[] args) {

      Test t = new Test();
      
      try {
         t.m1();
      } catch (ClassNotFoundException e) {
         System.err.println(e.getMessage());
      }
   }
}

No comments:

Post a Comment