SlideShare a Scribd company logo
1 of 18
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

More Related Content

What's hot

What's hot (20)

Java rmi
Java rmiJava rmi
Java rmi
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Applets
AppletsApplets
Applets
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Exception handling
Exception handlingException handling
Exception handling
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Finalize() method
Finalize() methodFinalize() method
Finalize() method
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
for loop in java
for loop in java for loop in java
for loop in java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Java threading
Java threadingJava threading
Java threading
 

Similar to Multi catch statement

Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaRajkattamuri
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Java class 7
Java class 7Java class 7
Java class 7Edureka!
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 

Similar to Multi catch statement (20)

Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
41c
41c41c
41c
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Presentation1
Presentation1Presentation1
Presentation1
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java class 7
Java class 7Java class 7
Java class 7
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 

More from myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

Multi catch statement

  • 1. The concept of multi-catch http://improvejava.blogspot.in/ 1
  • 2. 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
  • 3. 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
  • 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 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
  • 7. Explanation : • This program catches two exceptions, namely • ArithmeticException • ArrayIndexOutOfBoundsException http://improvejava.blogspot.in/ 7
  • 8. 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
  • 9. 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
  • 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 • 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
  • 12. 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 }
  • 13. 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
  • 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 can not raise more than one exception A. True B. False http://improvejava.blogspot.in/ 16
  • 17. Quiz 2. A throws clause 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