SlideShare a Scribd company logo
Exception Handling
What Is an Exception?
• Many developers are misguided by the term
exception handling. These developers believe
that the word exception is related to how
frequently something happens.
• For example, a developer designing a file Read
method is likely to say the following: “ When
reading from a file, you will eventually reach
the end of its data. Since reaching the end
will always happen, I’ll design my Read
method so that it reports the end by
returning a special value; I won’t have it
throw an exception.”
What’s Wrong?
• The problem with previous statement is that it is being
made by the developer designing the Read method,
not by the developer calling the Read method. When
designing the Read method, it is impossible for the
developer to know all of the possible situations in
which the method gets called.
• Therefore, the developer can’t possible know how
often the caller if the Read method will attempt to
read past the end of the file. In fact, since most files
contain structured data, attempting to read past the
end of a file is something that rarely happens.
What Exactly Is an
Exception?
• An exception means that an action member
cannot complete the task it was supposed to
perform as indicated by its name.
• Look at the following class definition:
class Account {
public static void Transfer(Account from,
Account to, float amount) {...
}
}
A Meaningful Exception
• The Transfer method accepts two Account
objects and a float value that identifiers an
amount of money to transfer between
accounts. The Transfer method could failed
for many reasons, like from or to argument
might be null.
• When the Transfer method is called, its code
must check for all the failed possibilities, and
if any of which is detected, it cannot transfer
the money and should notify the caller that it
failed by throwing an exception.
Validate Method’s Argument
• The Transfer method transfers money from
one account to another. If this method
doesn’t validate its arguments right away, the
method could subtract money from the from
account successfully, and then discover that
the to account argument is null.
• At this point, the method would throw an
exception because it cannot transfer that
money. However, the method must also add
that money back to the from account. If it
fails to do this, the state of the from account
is incorrect.
Don’t Catch Everything
• A ubiquitous mistake made by developers
who have not been properly trained on the
proper use of exceptions is to use catch blocks
too frequently and often improperly.
• When you catch an exception, you’re stating
that you expected this exception, you
understand why it occurred, and you know
how to deal with it. In other words, you’re
defining a policy for the application.
Don’t Catch Everything
(Cont’)
• This code indicates that it was
expecting any and all exceptions and
knows how to recover from any and all
situations.
try {
//try to execute code that the programmer
//knows might fail..
}
catch (exception) {
}
Don’t Catch Everything
(Cont’)
• A type that’s part of a class library should
never catch and swallow all exceptions
because there is no way for the type to know
exactly how the application intends to
respond to an exception.
• If the application code throws an exception,
another part of the application is probably
expecting to catch this exception. The
exception should be allowed to filter its way
up the call stack and let the application code
handle the exception as it sees fits.
Don’t Catch Everything
(Cont’)
• In addition, it is possible that an exception
was thrown because some object was in a bad
state. If library code catches and swallows the
exception, the program continues running
with unpredictable results and with potential
security vulnerabilities.
• It is better for the exception to be unhandled
and for the application to terminate.
Don’t Catch Everything
(Cont’)
• In fact, most unhandled exceptions will be
discovered during testing of your code. To fix
these unhandled exception, you will either
modify the code to look for specific
exception, or you will rewrite the code to
eliminate the conditions that cause the
exception to be thrown.
• The final version of the code that will be
running in a production environment should
see very few (if any) unhandled exceptions
and be extremely robust.
Exceptions and the
Java Virtual Machine
• When an exception takes place, the JVM
creates an exception object to identify the
type of exception that occurred
• The Throwable class is the super class of all
error and exception types generated by the
JVM or java programs
• Three Throwable subclass categories are
possible: Error, Runtime and Nonruntime
Exceptions
Exception Hierarchy
Errors
• Errors are events generated by the JVM
that have had a critical and fatal
impact on the running application.
• They are typically not handled by
regular programs
Runtime Exceptions
• Runtime (unchecked exceptions):
– Arithmetic Exceptions: dividing by zero
– Null Pointer Exceptions: attempting to
reference a method of a null pointer
– Class Cast Exception: casting incompatible
object, super or subclass types
– Index Out of Bounds Exception: accessing a
index value outside of an array range
– Typically result from logical errors
Java built-in exceptions
• ArithmeticException
• ArrayIndexOutOfBounds
• ArrayStore
• ClassCast
• IllegalArgument
• IllegalState
• IllegalThreadState
Checked Exceptions
• Nonruntime (checked exceptions):
– These exceptions occur outside of the runtime
system
– Input / Output exceptions
– Caught or specified by the system compiler
Exception Handling Terms
• throw – to generate an exception or to
describe an instance of an exception
• try – used to enclose a segment of code that
may produce a exception
• catch – placed directly after the try block to
handle one or more exception types
• finally – optional statement used after a try-
catch block to run a segment of code
regardless if a exception is generated
Handling Exceptions
try {
<code segment that may
throw an exception..>
} catch (ExceptionType) {
<exception handler..>
} catch (ExceptionType) {
<exception handler..>
} finally {
<optional code segment..>
}
Multiple catch statements
• Once a try statement has been used to
enclose a code segment, the catch can
be used to handle one or more specific
exception types. By defining catch
statements for specific exception types,
a more accurate handling of the
exception can be tailored to the
programs needs
Multiple catch statements
try {
<code segment that may
throw an exception..>
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(“File Not Found!”);
}
The finally statement
• The purpose of the optional finally statement
will allow the execution of a segment of code
regardless if the try statement throws an
exception or executes successfully
• The advantage of the finally statement is the
ability to clean up and release resources that
are utilized in the try segment of code that
might not be released in cases where an
exception has occurred
The finally statement
Define your own exception
• Here is a code sample showing how to define your own
exception.
• Define a classs:
public class EmptyStackException extends Exception { }
• Here is how you use the class:
public class Stack {
public Object Pop() throws EmptyStackException {
if (Empty()) throw new EmptyStackException();
...
}
}
• Note that you must use new to create an exception
object; you cannot just throw an exception.
Bibliography
• Jia, Xiaoping, Object Oriented Software
Development Using Java. Addison Wesley,
2003
• Horton, Ivor, Ivor Horton’s Beginning Java 2
JDK 5 Edition, Wiley Publishing, Inc. 2005
• http://java.sun.com/docs/books/tutorial/essentia
Bibliography
• Jeffrey Richter, CLR via C#, Second Edition.
Microsoft Press, 2006
• Horton, Ivor, Ivor Horton’s Beginning Java 2 JDK
5 Edition, Wiley Publishing, Inc. 2005
• http://java.sun.com/docs/books/tutorial/essential/ex
• Jia, Xiaoping, Object Oriented Software
Development Using Java. Addison Wesley, 2003

More Related Content

PDF
Exception handling
PPT
Exception handling and templates
PDF
Exception handling
PPSX
Exception Handling
PPTX
C++ ala
PPTX
Exception handling
PPTX
Exception Handling in C++
PPTX
What is Exception Handling?
Exception handling
Exception handling and templates
Exception handling
Exception Handling
C++ ala
Exception handling
Exception Handling in C++
What is Exception Handling?

What's hot (20)

PPTX
Exception handling chapter15
PPTX
Exception handling in java
PPTX
exception handling in cpp
PDF
14 exception handling
PPTX
130410107010 exception handling
PPT
Exception handler
PPT
Exception handling
PPTX
Exception handling c++
PPS
Exception handling in c programming
PPT
Exception handling in java
PDF
Exception Handling in the C++ Constructor
PPT
Exception Handling in JAVA
PPTX
Exception Handling in object oriented programming using C++
PPT
Week7 exception handling
PPT
Exception handling
PDF
javaexceptions
PPT
Exceptions in c++
PPT
Exception handling
PPTX
Presentation1
PPT
Understanding Exception Handling in .Net
Exception handling chapter15
Exception handling in java
exception handling in cpp
14 exception handling
130410107010 exception handling
Exception handler
Exception handling
Exception handling c++
Exception handling in c programming
Exception handling in java
Exception Handling in the C++ Constructor
Exception Handling in JAVA
Exception Handling in object oriented programming using C++
Week7 exception handling
Exception handling
javaexceptions
Exceptions in c++
Exception handling
Presentation1
Understanding Exception Handling in .Net
Ad

Similar to Exception handling (20)

PPTX
Java Exceptions and Exception Handling
PPTX
Exception handling
PPTX
Introduction to java exceptions
PPTX
Lecture 1 Try Throw Catch.pptx
PDF
Design byexceptions
PPTX
Exceptions in Java
PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
PPT
Exception
PPTX
Lecture 3.1.1 Try Throw Catch.pptx
PPTX
Training material exceptions v1
PPT
exceptionvdffhhhccvvvv-handling-in-java.ppt
PPTX
UNIT III 2021R.pptx
PPTX
UNIT III 2021R.pptx
PPTX
using Java Exception Handling in Java.pptx
PPT
exception-handling-in-java.ppt unit 2
PPTX
Exceptions overview
PPTX
PPT
Exception Handling Exception Handling Exception Handling
PPTX
Exceptionhandling
Java Exceptions and Exception Handling
Exception handling
Introduction to java exceptions
Lecture 1 Try Throw Catch.pptx
Design byexceptions
Exceptions in Java
Ch-1_5.pdf this is java tutorials for all
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
Exception
Lecture 3.1.1 Try Throw Catch.pptx
Training material exceptions v1
exceptionvdffhhhccvvvv-handling-in-java.ppt
UNIT III 2021R.pptx
UNIT III 2021R.pptx
using Java Exception Handling in Java.pptx
exception-handling-in-java.ppt unit 2
Exceptions overview
Exception Handling Exception Handling Exception Handling
Exceptionhandling
Ad

More from pooja kumari (10)

PPTX
Voice recognition
PPTX
PDF
DOCX
Introduction to linked lists
PPTX
Thread.ppt
PPTX
Thread.ppt
PPTX
Exception handling in java
PPTX
Exception handling in java
PPTX
Applet
DOCX
Sql seuence and sub queries
Voice recognition
Introduction to linked lists
Thread.ppt
Thread.ppt
Exception handling in java
Exception handling in java
Applet
Sql seuence and sub queries

Recently uploaded (20)

PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Institutional Correction lecture only . . .
PDF
01-Introduction-to-Information-Management.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
master seminar digital applications in india
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Cell Structure & Organelles in detailed.
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Types and Its function , kingdom of life
PDF
Basic Mud Logging Guide for educational purpose
PDF
Microbial disease of the cardiovascular and lymphatic systems
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Institutional Correction lecture only . . .
01-Introduction-to-Information-Management.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
master seminar digital applications in india
TR - Agricultural Crops Production NC III.pdf
Microbial diseases, their pathogenesis and prophylaxis
Cell Structure & Organelles in detailed.
O5-L3 Freight Transport Ops (International) V1.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
RMMM.pdf make it easy to upload and study
Cell Types and Its function , kingdom of life
Basic Mud Logging Guide for educational purpose
Microbial disease of the cardiovascular and lymphatic systems

Exception handling

  • 2. What Is an Exception? • Many developers are misguided by the term exception handling. These developers believe that the word exception is related to how frequently something happens. • For example, a developer designing a file Read method is likely to say the following: “ When reading from a file, you will eventually reach the end of its data. Since reaching the end will always happen, I’ll design my Read method so that it reports the end by returning a special value; I won’t have it throw an exception.”
  • 3. What’s Wrong? • The problem with previous statement is that it is being made by the developer designing the Read method, not by the developer calling the Read method. When designing the Read method, it is impossible for the developer to know all of the possible situations in which the method gets called. • Therefore, the developer can’t possible know how often the caller if the Read method will attempt to read past the end of the file. In fact, since most files contain structured data, attempting to read past the end of a file is something that rarely happens.
  • 4. What Exactly Is an Exception? • An exception means that an action member cannot complete the task it was supposed to perform as indicated by its name. • Look at the following class definition: class Account { public static void Transfer(Account from, Account to, float amount) {... } }
  • 5. A Meaningful Exception • The Transfer method accepts two Account objects and a float value that identifiers an amount of money to transfer between accounts. The Transfer method could failed for many reasons, like from or to argument might be null. • When the Transfer method is called, its code must check for all the failed possibilities, and if any of which is detected, it cannot transfer the money and should notify the caller that it failed by throwing an exception.
  • 6. Validate Method’s Argument • The Transfer method transfers money from one account to another. If this method doesn’t validate its arguments right away, the method could subtract money from the from account successfully, and then discover that the to account argument is null. • At this point, the method would throw an exception because it cannot transfer that money. However, the method must also add that money back to the from account. If it fails to do this, the state of the from account is incorrect.
  • 7. Don’t Catch Everything • A ubiquitous mistake made by developers who have not been properly trained on the proper use of exceptions is to use catch blocks too frequently and often improperly. • When you catch an exception, you’re stating that you expected this exception, you understand why it occurred, and you know how to deal with it. In other words, you’re defining a policy for the application.
  • 8. Don’t Catch Everything (Cont’) • This code indicates that it was expecting any and all exceptions and knows how to recover from any and all situations. try { //try to execute code that the programmer //knows might fail.. } catch (exception) { }
  • 9. Don’t Catch Everything (Cont’) • A type that’s part of a class library should never catch and swallow all exceptions because there is no way for the type to know exactly how the application intends to respond to an exception. • If the application code throws an exception, another part of the application is probably expecting to catch this exception. The exception should be allowed to filter its way up the call stack and let the application code handle the exception as it sees fits.
  • 10. Don’t Catch Everything (Cont’) • In addition, it is possible that an exception was thrown because some object was in a bad state. If library code catches and swallows the exception, the program continues running with unpredictable results and with potential security vulnerabilities. • It is better for the exception to be unhandled and for the application to terminate.
  • 11. Don’t Catch Everything (Cont’) • In fact, most unhandled exceptions will be discovered during testing of your code. To fix these unhandled exception, you will either modify the code to look for specific exception, or you will rewrite the code to eliminate the conditions that cause the exception to be thrown. • The final version of the code that will be running in a production environment should see very few (if any) unhandled exceptions and be extremely robust.
  • 12. Exceptions and the Java Virtual Machine • When an exception takes place, the JVM creates an exception object to identify the type of exception that occurred • The Throwable class is the super class of all error and exception types generated by the JVM or java programs • Three Throwable subclass categories are possible: Error, Runtime and Nonruntime Exceptions
  • 14. Errors • Errors are events generated by the JVM that have had a critical and fatal impact on the running application. • They are typically not handled by regular programs
  • 15. Runtime Exceptions • Runtime (unchecked exceptions): – Arithmetic Exceptions: dividing by zero – Null Pointer Exceptions: attempting to reference a method of a null pointer – Class Cast Exception: casting incompatible object, super or subclass types – Index Out of Bounds Exception: accessing a index value outside of an array range – Typically result from logical errors
  • 16. Java built-in exceptions • ArithmeticException • ArrayIndexOutOfBounds • ArrayStore • ClassCast • IllegalArgument • IllegalState • IllegalThreadState
  • 17. Checked Exceptions • Nonruntime (checked exceptions): – These exceptions occur outside of the runtime system – Input / Output exceptions – Caught or specified by the system compiler
  • 18. Exception Handling Terms • throw – to generate an exception or to describe an instance of an exception • try – used to enclose a segment of code that may produce a exception • catch – placed directly after the try block to handle one or more exception types • finally – optional statement used after a try- catch block to run a segment of code regardless if a exception is generated
  • 19. Handling Exceptions try { <code segment that may throw an exception..> } catch (ExceptionType) { <exception handler..> } catch (ExceptionType) { <exception handler..> } finally { <optional code segment..> }
  • 20. Multiple catch statements • Once a try statement has been used to enclose a code segment, the catch can be used to handle one or more specific exception types. By defining catch statements for specific exception types, a more accurate handling of the exception can be tailored to the programs needs
  • 21. Multiple catch statements try { <code segment that may throw an exception..> } catch (IOException e) { System.out.println(e.getMessage()); } catch (FileNotFoundException e) { System.out.println(“File Not Found!”); }
  • 22. The finally statement • The purpose of the optional finally statement will allow the execution of a segment of code regardless if the try statement throws an exception or executes successfully • The advantage of the finally statement is the ability to clean up and release resources that are utilized in the try segment of code that might not be released in cases where an exception has occurred
  • 24. Define your own exception • Here is a code sample showing how to define your own exception. • Define a classs: public class EmptyStackException extends Exception { } • Here is how you use the class: public class Stack { public Object Pop() throws EmptyStackException { if (Empty()) throw new EmptyStackException(); ... } } • Note that you must use new to create an exception object; you cannot just throw an exception.
  • 25. Bibliography • Jia, Xiaoping, Object Oriented Software Development Using Java. Addison Wesley, 2003 • Horton, Ivor, Ivor Horton’s Beginning Java 2 JDK 5 Edition, Wiley Publishing, Inc. 2005 • http://java.sun.com/docs/books/tutorial/essentia
  • 26. Bibliography • Jeffrey Richter, CLR via C#, Second Edition. Microsoft Press, 2006 • Horton, Ivor, Ivor Horton’s Beginning Java 2 JDK 5 Edition, Wiley Publishing, Inc. 2005 • http://java.sun.com/docs/books/tutorial/essential/ex • Jia, Xiaoping, Object Oriented Software Development Using Java. Addison Wesley, 2003