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);
}}}

More Related Content

What's hot (20)

PPTX
Exceptions in Java
Vadym Lotar
 
PPT
exceptions in java
javeed_mhd
 
PPTX
exception handling in cpp
gourav kottawar
 
PPT
Understanding Exception Handling in .Net
Mindfire Solutions
 
PPTX
What is Exception Handling?
Syed Bahadur Shah
 
PPT
Exception handling
Iblesoft
 
PDF
Exception handling
Ravi Sharda
 
PDF
Java unit3
Abhishek Khune
 
PPT
Exceptionhandling
DrHemlathadhevi
 
PDF
Best Practices in Exception Handling
Lemi Orhan Ergin
 
PPTX
Exception Handling in C++
Deepak Tathe
 
PPTX
Z blue exception
Narayana Swamy
 
PPT
Exceptions
Soham Sengupta
 
PPT
Exception handling in java
AmbigaMurugesan
 
PPT
Java: Exception
Tareq Hasan
 
PPTX
Chap2 exception handling
raksharao
 
PPT
Exception Handling Java
ankitgarg_er
 
PDF
JUnit & Mockito, first steps
Renato Primavera
 
PPT
Exception handling
zindadili
 
PPTX
Loop
prabhat kumar
 
Exceptions in Java
Vadym Lotar
 
exceptions in java
javeed_mhd
 
exception handling in cpp
gourav kottawar
 
Understanding Exception Handling in .Net
Mindfire Solutions
 
What is Exception Handling?
Syed Bahadur Shah
 
Exception handling
Iblesoft
 
Exception handling
Ravi Sharda
 
Java unit3
Abhishek Khune
 
Exceptionhandling
DrHemlathadhevi
 
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Exception Handling in C++
Deepak Tathe
 
Z blue exception
Narayana Swamy
 
Exceptions
Soham Sengupta
 
Exception handling in java
AmbigaMurugesan
 
Java: Exception
Tareq Hasan
 
Chap2 exception handling
raksharao
 
Exception Handling Java
ankitgarg_er
 
JUnit & Mockito, first steps
Renato Primavera
 
Exception handling
zindadili
 

Similar to 17 exception handling - ii (20)

PPTX
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
PPTX
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
PPTX
Java exception handling
Md. Tanvir Hossain
 
PPTX
Exception handling in java
yugandhar vadlamudi
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
Luis Goldster
 
PPT
Exception
Hoang Nguyen
 
PPT
Exception
Young Alista
 
PPT
Exception
James Wong
 
PPT
Exception
Harry Potter
 
PPTX
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
PPTX
Pi j4.2 software-reliability
mcollison
 
PPTX
L14 exception handling
teach4uin
 
PPT
8.Exception handling latest(MB).ppt .
happycocoman
 
PPTX
exception-handlinggygyygggy-in-java.pptx
SulbhaBhivsane
 
DOCX
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
PDF
Exception Handling notes in java exception
Ratnakar Mikkili
 
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Java exception handling
Md. Tanvir Hossain
 
Exception handling in java
yugandhar vadlamudi
 
Exception
Tony Nguyen
 
Exception
Tony Nguyen
 
Exception
Fraboni Ec
 
Exception
Fraboni Ec
 
Exception
Luis Goldster
 
Exception
Hoang Nguyen
 
Exception
Young Alista
 
Exception
James Wong
 
Exception
Harry Potter
 
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Pi j4.2 software-reliability
mcollison
 
L14 exception handling
teach4uin
 
8.Exception handling latest(MB).ppt .
happycocoman
 
exception-handlinggygyygggy-in-java.pptx
SulbhaBhivsane
 
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
Exception Handling notes in java exception
Ratnakar Mikkili
 
Ad

More from Ravindra Rathore (12)

PPTX
Lecture 5 phasor notations
Ravindra Rathore
 
PPT
Introduction of reflection
Ravindra Rathore
 
PDF
Line coding
Ravindra Rathore
 
PDF
28 networking
Ravindra Rathore
 
PDF
26 io -ii file handling
Ravindra Rathore
 
PDF
27 applet programming
Ravindra Rathore
 
PDF
22 multi threading iv
Ravindra Rathore
 
PDF
21 multi threading - iii
Ravindra Rathore
 
PDF
16 exception handling - i
Ravindra Rathore
 
PDF
15 bitwise operators
Ravindra Rathore
 
PDF
14 interface
Ravindra Rathore
 
PDF
Flipflop
Ravindra Rathore
 
Lecture 5 phasor notations
Ravindra Rathore
 
Introduction of reflection
Ravindra Rathore
 
Line coding
Ravindra Rathore
 
28 networking
Ravindra Rathore
 
26 io -ii file handling
Ravindra Rathore
 
27 applet programming
Ravindra Rathore
 
22 multi threading iv
Ravindra Rathore
 
21 multi threading - iii
Ravindra Rathore
 
16 exception handling - i
Ravindra Rathore
 
15 bitwise operators
Ravindra Rathore
 
14 interface
Ravindra Rathore
 
Ad

Recently uploaded (20)

PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 

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); }}}