SlideShare a Scribd company logo
Object – Oriented Programming
Week 13– Exception Handling
Ferdin Joe John Joseph, PhD
Faculty of Information Technology
Thai-Nichi Institute of Technology
Exception Handling
2
Motivations
When a program runs into a runtime error, the
program terminates abnormally.
How can you handle the runtime error so that
the program can continue to run or terminate
gracefully?
3
Exceptions
• Unexpected conditions
• Disrupt normal flow of program
• With exception handling, we can develop
more robust programs
4
Exceptions
Exceptions are thrown
And can be caught.
5
Where do exceptions come
from?
• JVM
OR
• Java Programs – can throw an exception
6
Exception Types
7
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System Errors
8
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Exceptions
9
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
Runtime Exceptions
10
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
Types of Exceptions
• Errors - serious and fatal problems
• Exceptions - can be thrown by any
program, user can extend
• RuntimException - caused by illegal
operations, thrown by JVM (unchecked)
11
Checked Exceptions vs.
Unchecked Exceptions
12
RuntimeException, Error and their subclasses are
known as unchecked exceptions.
All other exceptions are known as checked
exceptions - the compiler forces the programmer to
check and deal with the exceptions.
Checked or Unchecked Exceptions
13
LinkageError
Error
AWTError
AWTException
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Several more classes
Several more classes
Several more classes
IllegalArgumentException
Unchecked
exception.
Declaring, Throwing, and
Catching Exceptions
14
method1() {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
}
method2() throws Exception {
if (an error occurs) {
throw new Exception();
}
}
catch exception throw exception
declare exception
Checked Exceptions
Checked exceptions that can be thrown in a
method must be
• caught and handled
OR
• declared in the throws clause
15
Declaring Exceptions
Every method must state the types of
checked exceptions it might throw. This is
known as declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
16
Throwing Exceptions
When the program detects an error, the
program can create an instance of an
appropriate exception type and throw it. This
is known as throwing an exception. Here is
an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
17
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
18
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
19
Catching Exceptions
20
try
catch
try
catch
try
catch
An exception
is thrown in
method3
Call Stack
main method main method
method1
main method
method1
main method
method1
method2 method2
method3
Catch or Declare Checked
Exceptions
If a method declares a checked exception, you must invoke it in a try-
catch block or declare to throw the exception in the calling method.
In this example, method p1 invokes method p2 and p2 may throw a
checked exception (e.g., IOException)
21
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
(a) (b)
void p1() throws IOException {
p2();
}
Syntax
try {
// Normal execution path
throw new EmptyStackException();
} catch (ExampleException ee) {
// deal with the ExampleException
} finally {
// This optional section is executed upon termination of
any of the try or catch blocks above,
// except when System.exit() is called in "try" or "catch"
blocks;
}
Faculty of Information Technology,
Thai-Nichi Institute of Technology
22
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
23
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
24
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
25
animation
Suppose no
exceptions in the
statements
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
26
animation
The final block is
always executed
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
27
animation
Next statement in the
method is executed
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
28
animation
Suppose an exception
of type Exception1 is
thrown in statement2
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
29
animation
The exception is
handled.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
30
animation
The final block is
always executed.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
31
animation
The next statement in
the method is now
executed.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
32
animation
statement2 throws an
exception of type
Exception2.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
33
animation
Handling exception
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
34
animation
Execute the final block
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
35
animation
Rethrow the exception
and control is
transferred to the caller
Cautions When Using
Exceptions
• Exception handling separates error-
handling code from normal programming
tasks, thus making programs easier to read
and to modify.
• Exception handling usually requires more
time and resources because it requires
instantiating a new exception object, rolling
back the call stack, and propagating the
errors to the calling methods.
36
When to Throw Exceptions
• An exception occurs in a method.
• If you want the exception to be processed
by its caller, you should create an exception
object and throw it.
• If you can handle the exception in the
method where it occurs, there is no need to
throw it.
37
Creating Custom Exception
Classes
38
 Use the exception classes in the API whenever possible.
 Create custom exception classes if the predefined
classes are not sufficient.
 Declare custom exception classes by extending
Exception or a subclass of Exception.
Exceptions and Generics
• A generic class cannot extend Throwable.
• An Exception cannot be of a generic type.
39
Example 1
Faculty of Information Technology,
Thai-Nichi Institute of Technology
40
Example 1
Faculty of Information Technology,
Thai-Nichi Institute of Technology
41
Example 2
Faculty of Information Technology,
Thai-Nichi Institute of Technology
42

More Related Content

PDF
DSA 103 Object Oriented Programming :: Week 3
PDF
Constructors and Method Overloading
PPTX
PPTX
Inheritance in Java
PDF
Streams in Java 8
PDF
Diagramas de pacotes
PDF
Análise por Pontos de Função
PPTX
An Introduction to Unit Testing
DSA 103 Object Oriented Programming :: Week 3
Constructors and Method Overloading
Inheritance in Java
Streams in Java 8
Diagramas de pacotes
Análise por Pontos de Função
An Introduction to Unit Testing

What's hot (17)

PDF
Test unitaire
PPTX
Exception handling in java
PPTX
What is Kanban in Agile?
PPTX
Abstract Class & Abstract Method in Core Java
PPS
Introduction to class in java
PPTX
PPTX
Lecture 1 oop
PPT
Stratégie de tests type
PPTX
Presentation on software construction
PPTX
Unit No 3 Inheritance annd Polymorphism.pptx
PPTX
PPTX
White Box Testing And Control Flow & Loop Testing
PPTX
3.looping(iteration statements)
PDF
Software testing methods, levels and types
PPTX
Inter Thread Communicationn.pptx
PPT
C# Overriding
PPTX
Exceptionhandling
Test unitaire
Exception handling in java
What is Kanban in Agile?
Abstract Class & Abstract Method in Core Java
Introduction to class in java
Lecture 1 oop
Stratégie de tests type
Presentation on software construction
Unit No 3 Inheritance annd Polymorphism.pptx
White Box Testing And Control Flow & Loop Testing
3.looping(iteration statements)
Software testing methods, levels and types
Inter Thread Communicationn.pptx
C# Overriding
Exceptionhandling
Ad

Similar to Exception Handling (20)

PPT
JP ASSIGNMENT SERIES PPT.ppt
PPT
Exception handling
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling In Java Presentation. 2024
PPT
Exceptions in java
PPT
Java: Exception
PPTX
java exception.pptx
PDF
Exception Handling.pdf
PPSX
Exception hierarchy
PPTX
Java exception handling
PPTX
130410107010 exception handling
PPTX
Introduction to java exceptions
PPTX
12. Java Exceptions and error handling
PPT
exceptions in java
PPT
Exception and ErrorHandling in Java .ppt
PPT
Exception Handling
PPT
Exceptions in java
PPTX
Exception handling
PPT
Exceptions
PDF
7_exception.pdf
JP ASSIGNMENT SERIES PPT.ppt
Exception handling
Java-Exception Handling Presentation. 2024
Exception Handling In Java Presentation. 2024
Exceptions in java
Java: Exception
java exception.pptx
Exception Handling.pdf
Exception hierarchy
Java exception handling
130410107010 exception handling
Introduction to java exceptions
12. Java Exceptions and error handling
exceptions in java
Exception and ErrorHandling in Java .ppt
Exception Handling
Exceptions in java
Exception handling
Exceptions
7_exception.pdf
Ad

More from Ferdin Joe John Joseph PhD (20)

PDF
Invited Talk DGTiCon 2022
PDF
Week 12: Cloud AI- DSA 441 Cloud Computing
PDF
Week 11: Cloud Native- DSA 441 Cloud Computing
PDF
Week 10: Cloud Security- DSA 441 Cloud Computing
PDF
Week 9: Relational Database Service Alibaba Cloud- DSA 441 Cloud Computing
PDF
Week 7: Object Storage Service Alibaba Cloud- DSA 441 Cloud Computing
PDF
Week 6: Server Load Balancer and Auto Scaling Alibaba Cloud- DSA 441 Cloud Co...
PDF
Week 5: Elastic Compute Service (ECS) with Alibaba Cloud- DSA 441 Cloud Compu...
PDF
Week 4: Big Data and Hadoop in Alibaba Cloud - DSA 441 Cloud Computing
PDF
Week 3: Virtual Private Cloud, On Premise, IaaS, PaaS, SaaS - DSA 441 Cloud C...
PDF
Week 2: Virtualization and VM Ware - DSA 441 Cloud Computing
PDF
Week 1: Introduction to Cloud Computing - DSA 441 Cloud Computing
PDF
Sept 6 2021 BTech Artificial Intelligence and Data Science curriculum
PDF
Hadoop in Alibaba Cloud
PDF
Cloud Computing Essentials in Alibaba Cloud
PDF
Transforming deep into transformers – a computer vision approach
PDF
Week 11: Programming for Data Analysis
PDF
Week 10: Programming for Data Analysis
PDF
Week 9: Programming for Data Analysis
PDF
Week 8: Programming for Data Analysis
Invited Talk DGTiCon 2022
Week 12: Cloud AI- DSA 441 Cloud Computing
Week 11: Cloud Native- DSA 441 Cloud Computing
Week 10: Cloud Security- DSA 441 Cloud Computing
Week 9: Relational Database Service Alibaba Cloud- DSA 441 Cloud Computing
Week 7: Object Storage Service Alibaba Cloud- DSA 441 Cloud Computing
Week 6: Server Load Balancer and Auto Scaling Alibaba Cloud- DSA 441 Cloud Co...
Week 5: Elastic Compute Service (ECS) with Alibaba Cloud- DSA 441 Cloud Compu...
Week 4: Big Data and Hadoop in Alibaba Cloud - DSA 441 Cloud Computing
Week 3: Virtual Private Cloud, On Premise, IaaS, PaaS, SaaS - DSA 441 Cloud C...
Week 2: Virtualization and VM Ware - DSA 441 Cloud Computing
Week 1: Introduction to Cloud Computing - DSA 441 Cloud Computing
Sept 6 2021 BTech Artificial Intelligence and Data Science curriculum
Hadoop in Alibaba Cloud
Cloud Computing Essentials in Alibaba Cloud
Transforming deep into transformers – a computer vision approach
Week 11: Programming for Data Analysis
Week 10: Programming for Data Analysis
Week 9: Programming for Data Analysis
Week 8: Programming for Data Analysis

Recently uploaded (20)

PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PDF
Lecture1 pattern recognition............
PPTX
IB Computer Science - Internal Assessment.pptx
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PPTX
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PDF
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PPT
Quality review (1)_presentation of this 21
PPTX
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
PDF
annual-report-2024-2025 original latest.
PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PPTX
Business Acumen Training GuidePresentation.pptx
PDF
Business Analytics and business intelligence.pdf
PPTX
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
PPTX
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
PDF
Clinical guidelines as a resource for EBP(1).pdf
PPTX
Introduction to Knowledge Engineering Part 1
PDF
.pdf is not working space design for the following data for the following dat...
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
Lecture1 pattern recognition............
IB Computer Science - Internal Assessment.pptx
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
Galatica Smart Energy Infrastructure Startup Pitch Deck
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
Introduction-to-Cloud-ComputingFinal.pptx
Quality review (1)_presentation of this 21
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
annual-report-2024-2025 original latest.
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
Business Acumen Training GuidePresentation.pptx
Business Analytics and business intelligence.pdf
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
Clinical guidelines as a resource for EBP(1).pdf
Introduction to Knowledge Engineering Part 1
.pdf is not working space design for the following data for the following dat...

Exception Handling