SlideShare a Scribd company logo
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);
}}}
Ad

More Related Content

What's hot (20)

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
exceptions in java
exceptions in javaexceptions in java
exceptions in java
javeed_mhd
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
gourav kottawar
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
Mindfire 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 handling
Iblesoft
 
Exception handling
Exception handlingException handling
Exception handling
Ravi Sharda
 
Java unit3
Java unit3Java unit3
Java unit3
Abhishek Khune
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi 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 exception
Narayana Swamy
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 
Loop
LoopLoop
Loop
prabhat kumar
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
exceptions in java
exceptions in javaexceptions in java
exceptions in java
javeed_mhd
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
gourav kottawar
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
Mindfire Solutions
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Exception handling
Exception handlingException handling
Exception handling
Ravi Sharda
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
Deepak Tathe
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 

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
rohitgudasi18
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Young Alista
 
Exception
ExceptionException
Exception
James Wong
 
Exception
ExceptionException
Exception
Luis Goldster
 
Exception
ExceptionException
Exception
Harry Potter
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Hoang Nguyen
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
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-handlinggygyygggy-in-java.pptx
exception-handlinggygyygggy-in-java.pptxexception-handlinggygyygggy-in-java.pptx
exception-handlinggygyygggy-in-java.pptx
SulbhaBhivsane
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
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
rohitgudasi18
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
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-handlinggygyygggy-in-java.pptx
exception-handlinggygyygggy-in-java.pptxexception-handlinggygyygggy-in-java.pptx
exception-handlinggygyygggy-in-java.pptx
SulbhaBhivsane
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Ad

More from Ravindra Rathore (12)

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

Recently uploaded (20)

AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 

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); }}}
  翻译: