The concept of multi-catch




   http://improvejava.blogspot.in/   1
Objectives

On completion of this period, you would be able to
 know :
   • The concept of multi-catch statements
   • The usage of finally block
   • Related programs




                   http://improvejava.blogspot.in/   2
Recap

In the last class, you have studied about the usage of
   Java keywords
• We have also written simple program using try and
   catch




                  http://improvejava.blogspot.in/        3
Multiple catch Statements

1. Some times more than one exception can be
   raised

2. You can specify two or more catch blocks, each
   catching a different type of exception

3. When an exception is thrown, each catch block
   is inspected in order


                http://improvejava.blogspot.in/     4
Multiple catch Statements                     Contd..

1. First exception handler whose type matches that
   of the generated exception is executed
2. If any one catch statement executes, the others
   are bypassed, and execution continues after the
   try/catch block




                  http://improvejava.blogspot.in/             5
Java Program Using Multi-catch
// program for multiple catch statements
class MultiCatch {
    public static void main(String args[]) {
         try {
                   int a = args.length;
                   System.out.println("a = " + a);
                   int b = 42 / a;
                   int c[] = { 1 };
                   c[42] = 99;
         } catch(ArithmeticException e) {
                   System.out.println("Divide by 0: " + e);
         } catch(ArrayIndexOutOfBoundsException e) {
                   System.out.println("Array index Out of bounds: " + e);
         }
         System.out.println("After try/catch blocks.");
    }
}
                           http://improvejava.blogspot.in/                  6
Explanation :

• This program catches two exceptions, namely
   • ArithmeticException
   • ArrayIndexOutOfBoundsException




                    http://improvejava.blogspot.in/   7
throw Statement
• So far, we have dealt with exceptions that are
  thrown by Java run-time system
• It is possible for your program to throw an
  exception explicitly, using the throw statement
• The general form of throw is shown here
            throw exceptionObject;




                  http://improvejava.blogspot.in/   8
throws Clause

• A throws clause lists the types of exceptions that a
  method might throw
• This is necessary for all exceptions, except those of
  type Error or RuntimeException, or any of their
  subclasses
• All other exceptions that a method can throw must
  be declared in the throws clause




                    http://improvejava.blogspot.in/       9
throws Clause                          contd..

• General form of a method declaration that includes a
  throws type method
•     ret-type name(parameter-list) throws exception-list
      {
             // body of method
      }
• Here, exception-list is a comma-separated list of
  exception names

                   http://improvejava.blogspot.in/             10
finally Block
• finally block creates a block of code that will be
   executed after a try/catch block has completed
• And before the code following the try/catch block
• The finally block is compulsorily executed
   whether or not an exception is thrown
• If an exception is thrown, the finally block will
   execute even if no catch statement matches the
   exception
• finally block is useful for doing clean-up work
e.g. : To close an opened file
       To close a database connection etc

                   http://improvejava.blogspot.in/     11
An Example For finally Block
class finallyDemo {
   public static void main(String[] args){
          int [] a= new int [5];
          try{
                    for(int i=0; i<=5; i++){
                              a[i] = (i-1)/i;
                              System.out. println(a[i]);
                    }
          }catch (Exception e){
                    System. out. println(e);
          }finally{
                    System. out. println(“this line is certainly printed”);
          }
   }
                               http://improvejava.blogspot.in/                12
}
Explanation

• The above program ones finally block
• It generates ‘ArithmeticException’ as division by
  zero occurs
• The statement in finally block will be compulsorily
  executed




                   http://improvejava.blogspot.in/      13
Discussion

•   Give one situation for using multi-catch statement
•   In file processing
•   What is the purpose of ‘finally’ block
•   To do clean-up code
•   How many ‘finally’ block can be there for one try
    block
•   One is enough



                    http://improvejava.blogspot.in/
                              9CM604.45                  14
Summary

•   Some times more than one exception can be raised
•   You can specify two or more catch clauses, each
    catching a different type of exception
•   The finally block will execute whether or not an
    exception is thrown




                   http://improvejava.blogspot.in/     15
Quiz


1. We can not raise more than one exception

  A. True
  B. False




                  http://improvejava.blogspot.in/   16
Quiz


2. A throws clause lists the types of exceptions that a
   method might throw

   A. True
   B. False




                    http://improvejava.blogspot.in/       17
Frequently Asked Questions

1.   Explain the concept of multi-catch statements
2.   Explain how nested try statement can be used
3.   Explain the throw and throws clauses
4.   Write a sample Java program to demonstrate use
     of multiple catches




                    http://improvejava.blogspot.in/   18

Multi catch statement

  • 1.
    The concept ofmulti-catch http://improvejava.blogspot.in/ 1
  • 2.
    Objectives On completion ofthis period, you would be able to know : • The concept of multi-catch statements • The usage of finally block • Related programs http://improvejava.blogspot.in/ 2
  • 3.
    Recap In the lastclass, you have studied about the usage of Java keywords • We have also written simple program using try and catch http://improvejava.blogspot.in/ 3
  • 4.
    Multiple catch Statements 1.Some times more than one exception can be raised 2. You can specify two or more catch blocks, each catching a different type of exception 3. When an exception is thrown, each catch block is inspected in order http://improvejava.blogspot.in/ 4
  • 5.
    Multiple catch Statements Contd.. 1. First exception handler whose type matches that of the generated exception is executed 2. If any one catch statement executes, the others are bypassed, and execution continues after the try/catch block http://improvejava.blogspot.in/ 5
  • 6.
    Java Program UsingMulti-catch // program for multiple catch statements class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index Out of bounds: " + e); } System.out.println("After try/catch blocks."); } } http://improvejava.blogspot.in/ 6
  • 7.
    Explanation : • Thisprogram catches two exceptions, namely • ArithmeticException • ArrayIndexOutOfBoundsException http://improvejava.blogspot.in/ 7
  • 8.
    throw Statement • Sofar, we have dealt with exceptions that are thrown by Java run-time system • It is possible for your program to throw an exception explicitly, using the throw statement • The general form of throw is shown here throw exceptionObject; http://improvejava.blogspot.in/ 8
  • 9.
    throws Clause • Athrows clause lists the types of exceptions that a method might throw • This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses • All other exceptions that a method can throw must be declared in the throws clause http://improvejava.blogspot.in/ 9
  • 10.
    throws Clause contd.. • General form of a method declaration that includes a throws type method • ret-type name(parameter-list) throws exception-list { // body of method } • Here, exception-list is a comma-separated list of exception names http://improvejava.blogspot.in/ 10
  • 11.
    finally Block • finallyblock creates a block of code that will be executed after a try/catch block has completed • And before the code following the try/catch block • The finally block is compulsorily executed whether or not an exception is thrown • If an exception is thrown, the finally block will execute even if no catch statement matches the exception • finally block is useful for doing clean-up work e.g. : To close an opened file To close a database connection etc http://improvejava.blogspot.in/ 11
  • 12.
    An Example Forfinally Block class finallyDemo { public static void main(String[] args){ int [] a= new int [5]; try{ for(int i=0; i<=5; i++){ a[i] = (i-1)/i; System.out. println(a[i]); } }catch (Exception e){ System. out. println(e); }finally{ System. out. println(“this line is certainly printed”); } } http://improvejava.blogspot.in/ 12 }
  • 13.
    Explanation • The aboveprogram ones finally block • It generates ‘ArithmeticException’ as division by zero occurs • The statement in finally block will be compulsorily executed http://improvejava.blogspot.in/ 13
  • 14.
    Discussion • Give one situation for using multi-catch statement • In file processing • What is the purpose of ‘finally’ block • To do clean-up code • How many ‘finally’ block can be there for one try block • One is enough http://improvejava.blogspot.in/ 9CM604.45 14
  • 15.
    Summary • Some times more than one exception can be raised • You can specify two or more catch clauses, each catching a different type of exception • The finally block will execute whether or not an exception is thrown http://improvejava.blogspot.in/ 15
  • 16.
    Quiz 1. We cannot raise more than one exception A. True B. False http://improvejava.blogspot.in/ 16
  • 17.
    Quiz 2. A throwsclause lists the types of exceptions that a method might throw A. True B. False http://improvejava.blogspot.in/ 17
  • 18.
    Frequently Asked Questions 1. Explain the concept of multi-catch statements 2. Explain how nested try statement can be used 3. Explain the throw and throws clauses 4. Write a sample Java program to demonstrate use of multiple catches http://improvejava.blogspot.in/ 18