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
Ad

More Related Content

What's hot (20)

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 java
priyankazope
 
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
Md.Shohel Rana ( M.Sc in CSE Khulna University of Engineering & Technology (KUET))
 
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
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
Ravindra Rathore
 
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
Exception
Марія Русин
 

Viewers also liked (9)

Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
PRN USM
 
Canales televisión total
Canales televisión totalCanales televisión total
Canales televisión total
C & C Ingenieros Arequipa
 
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 Mhpb
PRN 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
 
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 Mhpb
PRN USM
 
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
 
Ad

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
AKSHAYBHABAD5
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
L12.2 Exception handling.pdf
L12.2  Exception handling.pdfL12.2  Exception handling.pdf
L12.2 Exception handling.pdf
MaddalaSeshu
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh 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 handling
BHUVIJAYAVELU
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
Ravindra 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
 
Java unit3
Java unit3Java unit3
Java unit3
Abhishek Khune
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
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
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
L12.2 Exception handling.pdf
L12.2  Exception handling.pdfL12.2  Exception handling.pdf
L12.2 Exception handling.pdf
MaddalaSeshu
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh 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 handling
BHUVIJAYAVELU
 
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 - ii
Ravindra 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
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Ad

More from PRN USM (12)

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 Homes
PRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
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
 
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
PRN 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 Control
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
 
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 Homes
PRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
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
 
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
PRN 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 Control
PRN USM
 

Recently uploaded (20)

Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 

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

  • #4: 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.
  • #6: 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.
  • #9: 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.
  • #10: 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.
  • #11: 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.
  • #12: 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.
  • #13: 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.
  • #14: 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.
  • #15: 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.
  • #16: 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.
  • #17: 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.
  • #18: 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.
  • #19: 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.
  • #20: 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.
  • #21: It is possible to throw an exception from our own method.
  • #22: We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly.
  • #24: 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.
  • #27: 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.
  • #28: 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.