SlideShare a Scribd company logo
1 of 13
Download to read offline
Using try and catch
• If we handle error manually, it gives two benefits. First, it allows us
to fix the error. Second, it prevents the program from automatically
terminating.
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d ;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero."); }
System.out.println("After catch statement."); } }
• This program generates the following output:
Division by zero.
After catch statement.
• In some cases, more than one exception could be raised by a
single piece of code. To handle this type of situation, we can
specify two or more catch clauses, each catching a different type
of exception.
• When an exception is thrown, each catch statement is inspected
in order, and the first one whose type matches that of the
exception is executed. After one catch statement executes, the
others are bypassed, and execution continues after the try/catch
block.
• The try statement can be nested. Each time a try statement is
entered, the context of that exception is pushed on the stack.
• If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match. If no catch
statement matches, then the Java run-time system will handle
the exception.
Displaying the description of the
Exception
• Throwable overrides the toString( ) method
(defined by Object) so that it returns a string
containing a description of the exception. You
can display this description in a println( )
statement by simply passing the exception as
an argument.for example.
catch (ArithmeticException e){
System.out.println("Exception: " + e);
}
Multiple catch clauses……………
• In some cases, more than one exception could be
raised by a single piece of code from the try block.
• you can specify two or more catch clauses, each
catching a different type of exception.
• When an exception is thrown, each catch statement is
inspected in order, and the first one whose type
matches that of the exception is executed.
• After one catch statement executes, the others are
bypassed, and execution continues after the try/catch
block.
// Demonstrate 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 oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Output
C:>javac MultiCatch.java
C:>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:>java MultiCatch TestArg
a = 1
Array index
oob:java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
• When you use multiple catch statements, it is
important to remember that exception
subclasses must come before any of their
super classes. This is because a
• catch statement that uses a superclass will
catch exceptions of that type plus any of its
subclasses. Thus, a subclass would never be
reached if it came after its superclass.
• Further, in Java, unreachable code is an error.
For example, consider the following.
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}catch(ArithmeticException e) {
System.out.println("This is never reached.");
}
}
}
Since ArithmeticException is a subclass of Exception, the first catch
statement will handle all Exception-based errors, including
ArithmeticException. This means that the second catch statement will never
execute.
Nested try block……
• The try statement can be nested.
• That is, a try statement can be inside the block of another try.
Each time a try statement is entered, the context of that
exception is pushed on the stack.
• If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
• This continues until one of the catch statements succeeds, or
until all of the nested try statements are exhausted.
• If no catch statement matches, then the Java run-time system
will handle the exception.
• Here is an example that uses nested try statements:
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try {
if(a==1) a = a/(a-a);
if(a==2) {
int c[] = { 1 };
c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Output…
C:>javac NestTry
C:>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
Nested try catch within the method.
• Nesting of try statements can occur in less
obvious ways when method calls are involved.
• For example, you can enclose a call to a
method within a try block. Inside that method
is another try statement. In this case, the try
within the method is still nested inside the
outer try block, which calls the method.
class MethNestTry {
static void nesttry(int a) {
try { if(a==1) a = a/(a-a); // division by zero
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}}}

More Related Content

What's hot

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
exceptions in java
exceptions in javaexceptions in java
exceptions in javajaveed_mhd
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .NetMindfire Solutions
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?Syed Bahadur Shah
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception HandlingLemi Orhan Ergin
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exceptionNarayana Swamy
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Java: Exception
Java: ExceptionJava: Exception
Java: ExceptionTareq Hasan
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 

What's hot (20)

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
exceptions in java
exceptions in javaexceptions in java
exceptions in java
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exceptions
ExceptionsExceptions
Exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Exception handling
Exception handlingException handling
Exception handling
 
Loop
LoopLoop
Loop
 

Similar to 17 exception handling - ii

Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java yugandhar vadlamudi
 
Exception
ExceptionException
ExceptionFraboni Ec
 
Exception
ExceptionException
ExceptionFraboni Ec
 
Exception
ExceptionException
ExceptionJames Wong
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
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
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 

Similar to 17 exception handling - ii (20)

Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 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 .
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 

More from Ravindra Rathore

More from Ravindra Rathore (12)

Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notations
 
Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection
 
Line coding
Line coding Line coding
Line coding
 
28 networking
28  networking28  networking
28 networking
 
26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
21 multi threading - iii
21 multi threading - iii21 multi threading - iii
21 multi threading - iii
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
15 bitwise operators
15 bitwise operators15 bitwise operators
15 bitwise operators
 
14 interface
14  interface14  interface
14 interface
 
Flipflop
FlipflopFlipflop
Flipflop
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

17 exception handling - ii

  • 1. Using try and catch • If we handle error manually, it gives two benefits. First, it allows us to fix the error. Second, it prevents the program from automatically terminating. class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d ; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } • This program generates the following output: Division by zero. After catch statement.
  • 2. • In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type of exception. • When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. • The try statement can be nested. Each time a try statement is entered, the context of that exception is pushed on the stack. • If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. If no catch statement matches, then the Java run-time system will handle the exception.
  • 3. Displaying the description of the Exception • Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception. You can display this description in a println( ) statement by simply passing the exception as an argument.for example. catch (ArithmeticException e){ System.out.println("Exception: " + e); }
  • 4. Multiple catch clauses…………… • In some cases, more than one exception could be raised by a single piece of code from the try block. • you can specify two or more catch clauses, each catching a different type of exception. • When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. • After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
  • 5. // Demonstrate 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 oob: " + e); } System.out.println("After try/catch blocks."); } }
  • 6. Output C:>javac MultiCatch.java C:>java MultiCatch a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks. C:>java MultiCatch TestArg a = 1 Array index oob:java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.
  • 7. • When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their super classes. This is because a • catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. • Further, in Java, unreachable code is an error. For example, consider the following.
  • 8. class SuperSubCatch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("Generic Exception catch."); }catch(ArithmeticException e) { System.out.println("This is never reached."); } } } Since ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-based errors, including ArithmeticException. This means that the second catch statement will never execute.
  • 9. Nested try block…… • The try statement can be nested. • That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. • If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. • This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. • If no catch statement matches, then the Java run-time system will handle the exception. • Here is an example that uses nested try statements:
  • 10. class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); try { if(a==1) a = a/(a-a); if(a==2) { int c[] = { 1 }; c[42] = 99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } }
  • 11. Output… C:>javac NestTry C:>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One a = 1 Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException
  • 12. Nested try catch within the method. • Nesting of try statements can occur in less obvious ways when method calls are involved. • For example, you can enclose a call to a method within a try block. Inside that method is another try statement. In this case, the try within the method is still nested inside the outer try block, which calls the method.
  • 13. class MethNestTry { static void nesttry(int a) { try { if(a==1) a = a/(a-a); // division by zero if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); nesttry(a); } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); }}}