SlideShare a Scribd company logo
Exceptions
Objectives
 After you have read and studied this
chapter, you should be able to
Improve the reliability of code by
incorporating exception-handling.
Implement the try-catch blocks for catching
and handling exceptions.
Write methods that propagate exceptions.
Distinguish the checked and unchecked, or
runtime, exceptions.
Definition
 An exception represents an error
condition that can occur during the
normal course of program execution.
 Examples
Division by zero
Trying to open an input file that does not
exist
An array index that goes out of bounds
Java’s Mechanism of Exception
Handling
 When an exception occurs, an object of a
particular exception class can be created
and thrown.
 The exception-handling routine can then be
executed to catch & handle the exception
object; we say the thrown exception is caught.
 The normal sequence of flow is terminated if
the exception object is thrown.
Exception thrown
Scanner scan = new Scanner(System.in);
int num = 0;
System.out.print(“Enter an integer>”);
num = scan.nextInt();
System.out.println(“The number you entered is “ +num);
Enter an integer> three
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ExceptionTest.main(ExceptionTest.java:11)
Error message for invalid input
Java’s Mechanism of
Exception Handling
(continued) Java provides a number of exception
classes to effectively handle certain
common exceptions such as division by
zero, invalid input, and file not found
Example:
 When a Scanner object is used to input
data into a program, any invalid input
errors are handled using the class
InputMismatchException
 When a division by zero exception occurs,
the program creates an object of the
class ArithmeticException
Exception Types
 All types of thrown exception objects are
instances of the Throwable class or its
subclasses.
 Serious errors are represented by instances of the
Error class or its subclasses.
 Exceptional cases that common applications
should handle are represented by instances of the
Exception class or its subclasses.
Throwable Hierarchy
 There are over 60 classes in the hierarchy.
Catching an Exception
To catch an exception:
•Put code that might throw an exception inside a try{} block.
•Put code that handles the exception inside a catch{} block.
Use try{} and catch{} block
try {
// statements, some of which might
// throw an exception
}
catch ( SomeExceptionType ex ) {
// statements to handle this
// type of exception
}
Catching an Exception
Scanner scan = new Scanner(System.in);
int num = 0;
try {
System.out.print(“Enter an integer>”);
num = scan.nextInt();
} catch (InputMismatchException e){
System.out.println(“Invalid input! Please enter
digits only");
}
System.out.println(“The number you entered is “ +num);
try
catch
try-catch Control Flow
Getting Information
 There are two methods we can call to
get information about the thrown
exception:
getMessage
printStackTracetry {
. . .
} catch (NumberFormatException e){
System.out.println(e.getMessage());
System.out.println(e.printStackTrace());
}
Multiple catch Blocks
 A single try-catch statement can include multiple catch
blocks, one for each type of exception.
try {
. . .
age = Integer.parseInt(inputStr);
. . .
val = cal.get(id);
. . .
} catch (NumberFormatException e){
. . .
} catch (ArrayIndexOutOfBoundsException e){
. . .
}
Multiple catch Control Flow
-Only one catch{} block gets control (the first block that matches the type of the exception ).
-If no catch{} block matches the exception, none is picked (just as if there were no try{} block.)
Multiple catch Control Flow
•The most specific exception types should appear first in the structure,
followed by the more general exception types.
A child class should appear before any of its ancestors. If class A is not
an ancestor or descendant of class B, then it doesn't matter which appears first.
Eg. the following is wrong:
try {
...
} catch (Exception ex ) {
. . .
} catch (ArithmeticException ex ) {
. . .
}
Multiple catch Control Flow
Question: Is this ok?:
try {
...
} catch (NumberFormatException ex ) {
. . .
} catch (ArithmeticException ex ) {
. . .
}
The finally Block
 There are situations where we need to take certain actions regardless
of whether an exception is thrown or not.
 We place statements that must be executed regardless of exceptions
in the finally block.
try {
// statements, some of which might
// throw an exception
} catch ( SomeExceptionType ex ) {
// statements to handle this
// type of exception
} catch ( AnotherExceptionType ex ) {
// statements to handle this
// type of exception
} finally {
// statements which will execute no matter
// how the try block was exited.
}
try-catch-finally Control Flow
Propagating Exceptions
 Instead of catching a thrown exception by using the
try-catch statement, we can propagate the thrown
exception back to the caller of our method.
 The method header includes the reserved word
throws.
public int getAge( ) throws NumberFormatException {
. . .
int age = Integer.parseInt(inputStr);
. . .
return age;
}
Throwing Exceptions
 We can write a method that throws an exception
directly, i.e., this method is the origin of the exception.
 Use the throw reserved to create a new instance of the
Exception or its subclasses.
 The method header includes the reserved word
throws.
public void doWork(int num) throws Exception {
. . .
if (num != val) throw new Exception("Invalid val");
. . .
}
Exception Thrower
 When a method may throw an
exception, either directly or indirectly, we
call the method an exception thrower.
 Every exception thrower must be one of
two types:
 catcher.
 propagator.
Types of Exception Throwers
 An exception catcher is an exception
thrower that includes a matching catch
block for the thrown exception.
 An exception propagator does not
contain a matching catch block.
 A method may be a catcher of one
exception and a propagator of another.
Sample Call Sequence
Checked vs. Unchecked Exception
 There are two types of exceptions:
 Checked.
 Unchecked.
 A checked exception is an exception
that is checked at compile time, so it
must be handled.
 An unchecked exception is not checked
at compile time, so no need to handle
(optional).
 unchecked exception include Error and
RuntimeException and their subclasses.
 checked exception include Exception
Different Handling Rules
 When calling a method that can throw
checked exceptions
use the try-catch statement and place the
call in the try block, or
modify the method header to include the
appropriate throws clause.
 When calling a method that can throw
runtime exceptions, it is optional to use
the try-catch statement or modify the
method header to include a throws
clause.
Handling Checked Exceptions
Handling Runtime Exceptions

More Related Content

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
Kunal Singh
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
atozknowledge .com
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exception
ExceptionException

What's hot (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception
ExceptionException
Exception
 

Viewers also liked

Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
PRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
PRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From MhpbPRN USM
 
666 Chip
666 Chip666 Chip
666 Chip
connimaddox
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
PRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
PRN USM
 

Viewers also liked (9)

Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Canales televisión total
Canales televisión totalCanales televisión total
Canales televisión total
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 
666 Chip
666 Chip666 Chip
666 Chip
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 

Similar to Exception Handling

unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
L12.2 Exception handling.pdf
L12.2  Exception handling.pdfL12.2  Exception handling.pdf
L12.2 Exception handling.pdf
MaddalaSeshu
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdf
lsdfjldskjf
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
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
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
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
 

Similar to Exception Handling (20)

unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
L12.2 Exception handling.pdf
L12.2  Exception handling.pdfL12.2  Exception handling.pdf
L12.2 Exception handling.pdf
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdf
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 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 .
 

More from PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Array
ArrayArray
Array
PRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
PRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree HomesPRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean ExperiencePRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesPRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlPRN USM
 

More from PRN USM (12)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Array
ArrayArray
Array
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 

Recently uploaded

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 

Recently uploaded (20)

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

Exception Handling

  • 2. Objectives  After you have read and studied this chapter, you should be able to Improve the reliability of code by incorporating exception-handling. Implement the try-catch blocks for catching and handling exceptions. Write methods that propagate exceptions. Distinguish the checked and unchecked, or runtime, exceptions.
  • 3. Definition  An exception represents an error condition that can occur during the normal course of program execution.  Examples Division by zero Trying to open an input file that does not exist An array index that goes out of bounds
  • 4. Java’s Mechanism of Exception Handling  When an exception occurs, an object of a particular exception class can be created and thrown.  The exception-handling routine can then be executed to catch & handle the exception object; we say the thrown exception is caught.  The normal sequence of flow is terminated if the exception object is thrown.
  • 5. Exception thrown Scanner scan = new Scanner(System.in); int num = 0; System.out.print(“Enter an integer>”); num = scan.nextInt(); System.out.println(“The number you entered is “ +num); Enter an integer> three Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ExceptionTest.main(ExceptionTest.java:11) Error message for invalid input
  • 6. Java’s Mechanism of Exception Handling (continued) Java provides a number of exception classes to effectively handle certain common exceptions such as division by zero, invalid input, and file not found Example:  When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException  When a division by zero exception occurs, the program creates an object of the class ArithmeticException
  • 7. Exception Types  All types of thrown exception objects are instances of the Throwable class or its subclasses.  Serious errors are represented by instances of the Error class or its subclasses.  Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses.
  • 8. Throwable Hierarchy  There are over 60 classes in the hierarchy.
  • 9. Catching an Exception To catch an exception: •Put code that might throw an exception inside a try{} block. •Put code that handles the exception inside a catch{} block. Use try{} and catch{} block try { // statements, some of which might // throw an exception } catch ( SomeExceptionType ex ) { // statements to handle this // type of exception }
  • 10. Catching an Exception Scanner scan = new Scanner(System.in); int num = 0; try { System.out.print(“Enter an integer>”); num = scan.nextInt(); } catch (InputMismatchException e){ System.out.println(“Invalid input! Please enter digits only"); } System.out.println(“The number you entered is “ +num); try catch
  • 12. Getting Information  There are two methods we can call to get information about the thrown exception: getMessage printStackTracetry { . . . } catch (NumberFormatException e){ System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); }
  • 13. Multiple catch Blocks  A single try-catch statement can include multiple catch blocks, one for each type of exception. try { . . . age = Integer.parseInt(inputStr); . . . val = cal.get(id); . . . } catch (NumberFormatException e){ . . . } catch (ArrayIndexOutOfBoundsException e){ . . . }
  • 14. Multiple catch Control Flow -Only one catch{} block gets control (the first block that matches the type of the exception ). -If no catch{} block matches the exception, none is picked (just as if there were no try{} block.)
  • 15. Multiple catch Control Flow •The most specific exception types should appear first in the structure, followed by the more general exception types. A child class should appear before any of its ancestors. If class A is not an ancestor or descendant of class B, then it doesn't matter which appears first. Eg. the following is wrong: try { ... } catch (Exception ex ) { . . . } catch (ArithmeticException ex ) { . . . }
  • 16. Multiple catch Control Flow Question: Is this ok?: try { ... } catch (NumberFormatException ex ) { . . . } catch (ArithmeticException ex ) { . . . }
  • 17. The finally Block  There are situations where we need to take certain actions regardless of whether an exception is thrown or not.  We place statements that must be executed regardless of exceptions in the finally block. try { // statements, some of which might // throw an exception } catch ( SomeExceptionType ex ) { // statements to handle this // type of exception } catch ( AnotherExceptionType ex ) { // statements to handle this // type of exception } finally { // statements which will execute no matter // how the try block was exited. }
  • 19. Propagating Exceptions  Instead of catching a thrown exception by using the try-catch statement, we can propagate the thrown exception back to the caller of our method.  The method header includes the reserved word throws. public int getAge( ) throws NumberFormatException { . . . int age = Integer.parseInt(inputStr); . . . return age; }
  • 20. Throwing Exceptions  We can write a method that throws an exception directly, i.e., this method is the origin of the exception.  Use the throw reserved to create a new instance of the Exception or its subclasses.  The method header includes the reserved word throws. public void doWork(int num) throws Exception { . . . if (num != val) throw new Exception("Invalid val"); . . . }
  • 21. Exception Thrower  When a method may throw an exception, either directly or indirectly, we call the method an exception thrower.  Every exception thrower must be one of two types:  catcher.  propagator.
  • 22. Types of Exception Throwers  An exception catcher is an exception thrower that includes a matching catch block for the thrown exception.  An exception propagator does not contain a matching catch block.  A method may be a catcher of one exception and a propagator of another.
  • 24. Checked vs. Unchecked Exception  There are two types of exceptions:  Checked.  Unchecked.  A checked exception is an exception that is checked at compile time, so it must be handled.  An unchecked exception is not checked at compile time, so no need to handle (optional).  unchecked exception include Error and RuntimeException and their subclasses.  checked exception include Exception
  • 25. Different Handling Rules  When calling a method that can throw checked exceptions use the try-catch statement and place the call in the try block, or modify the method header to include the appropriate throws clause.  When calling a method that can throw runtime exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause.

Editor's Notes

  1. We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop. One way to do this is to wrap the statements that may throw an exception with the try-catch control statement.
  2. Consider the given example. What would happen if the user enters a value such as the text 'ten' instead of 10? The parseInt method cannot convert such an input to an internal numerical format. This type of error is called an exception, and it will result in displaying an error message such as the one shown here. We say the parseInt method has thrown a NumberFormatException.
  3. The classes shown here are some of the more common classes in the Throwable class hierarchy. We will be seeing most of the Exception and its subclasses shown here in the later modules.
  4. This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
  5. This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
  6. This illustrates how the control flows when there is an exception and when there is no exception. In the case when no statements in the try block throw an exception, then the catch block is skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  7. In the previous example, we simply displayed a fixed error message. We can get display a more generic error message by using the getMessage or printStrackTrace methods. We will experiment with these methods in the lab.
  8. In this example, we see two statements in the try block that can potentially throw exceptions. The parseInt method throws a NumberFormatException while the get method throws an ArrayIndexOutOfBoundsException when the argument id is outside the range of valid values.
  9. Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  10. Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  11. Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  12. The finally block is not used often in introductory level programs, but we will introduce them here for the sake of complete coverage of the topic. For example, suppose we open a communication channel from our Java program to a remote web server to exchange data. If the data exchange is successfully completed in the try block, then we close the communication channel and finish the operation. If the data exchange is interrupted for some reason, an exception is thrown and the operation is aborted. In this case also, we need to close the communication channel, because leaving the channel open by one application blocks other applications from using it. The code to close the communication channel should therefore be placed in the finally block.
  13. Here's how the control flows when there are multiple catch blocks and the finally block. In the case when no statements in the try block throw an exception, then all catch blocks are skipped, but the statements in the finally block are executed. Execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed first and the statements in the finally block are executed next. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
  14. Using the try-catch statement is the first way to handle the exceptions. The second way is to propagate the thrown exception back to the caller of the method. The method that includes the statement that calls our method must either catch it or propagate it back to their caller.
  15. It is possible to throw an exception from our own method.
  16. We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly.
  17. This illustration shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack.
  18. Callers of a method that can throw a checked exception must include the try-catch statement in the method body or the throws clause in the header.
  19. It is optional for callers of a method that can throw runtime exceptions to include the try-catch statement in the method body or the throws clause in the header.