SlideShare a Scribd company logo
Exception Handling
Goals
 To learn how to throw exceptions
 To be able to design your own exception
classes
 To understand the difference between
checked and unchecked exceptions
 To learn how to catch exceptions
 To know when and where to catch an
exception
Separating Error Handling Code
 Traditional approach to error handling: method returns
error code
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
 What happens if
the file can't be opened?
the length of the file can't be determined?
enough memory can't be allocated?
if the read fails?
if the file can't be closed?
 To answer, you'd have to add a lot of code to do error
detection, reporting and handling
Separating Error Handling Code
errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else { errorCode = -2; }
} else { errorCode = -3; }
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else { errorCode = errorCode and -4; }
} else { errorCode = -5; }
return errorCode;
}
The Alternative: Exception Handling
 Exceptions enable to write the main flow of code and deal with the,
well, exceptional cases elsewhere
readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
catch (fileOpenFailed) { doSomething; }
catch (sizeDeterminationFailed) { doSomething; }
catch (memoryAllocationFailed) { doSomething; }
catch (readFailed) { doSomething; }
catch (fileCloseFailed) { doSomething; }
}
Propagating Errors Up the Call Stack
 Exceptions enable you to propagate error reporting up the call stack of
methods
method1 {
errorCodeType error;
error = call method2;
if (error) doErrorProcessing;
else proceed;
}
errorCodeType method2 {
errorCodeType error;
error = call method3;
if (error) return error;
else proceed;
}
errorCodeType method3 {
errorCodeType error;
error = call readFile;
if (error) return error;
else proceed;
}
Propagating Errors Up the Call Stack
 The Java runtime system searches backwards through
the call stack to find any methods that are interested in
handling a particular exception
method1 {
try {
call method2;
} catch (exception) { doErrorProcessing; }
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
Grouping Error Types and Error
Differentiation
 Exceptions fall into
categories or groups.
Using Exceptions
 The throw clause
• Exceptions originate within a method or block of code
using the throw clause
throw someThrowableObject;
 The throws clause
• Specifies that the method can throw Exception(s)
public Object pop()
throws EmptyStackException {}
Using Exceptions
 The try block
• is used to wrap or enclose code where
exceptions may occur
 The catch block
• A method can catch an exception by providing
an exception handler for that type of
exception
• Typically, a catch block is created for each
type of exception that can occur.
The finally Clause
 Exception terminates current method
 Danger: Can skip over essential code
BufferedReader in =
new BufferedReader(
new FileReader(filename));
purse.read(in);
in.close();
 Must execute in.close() even if exception
happens
 Use finally clause for code that must be
executed "no matter what"
Example: Catching Exceptions
public void openAfile() {
try {
// Next two lines may generate an exception.
BufferedReader br =
new BufferedReader(
new FileReader ("aFile.txt"));
String s = br.readLine();
br.close();
// If no exceptions occur the following line
// will be executed.
System.out.println ("open File returned normally");
} catch (FileNotFoundException e) {
System.out.println ("Cannot find file to open!");
} catch (IOException e) {
System.out.println ("IOException: " + e);
} finally {
try { if (br != null) br.close();
} catch (IOException e) { };
}
}
Example: Declaring Exceptions
public static void main (String args[]) {
try {
openAfile();
} catch (FileNotFoundException e) {
System.out.println ("Cannot find file to open!");
} catch (IOException e) {
System.out.println ("IOException: " + e);
}
}
public static void openAfile()
throws FileNotFoundException, IOException {
// Next two lines may generate an exception.
BufferedReader br = new BufferedReader(
new FileReader("aFile.txt"));
String s = br.readLine();
br.close();
System.out.println("openAFile returned normally");
}
Exception Specification
 Java exceptions are of different types including
I/O Exceptions, runtime exceptions, and
exceptions of your own creation
• Runtime exceptions occur within the JRE, includes:
arithmetic exceptions, pointer exceptions, and
indexing exceptions
• The compiler does not require that you catch or specify
runtime exceptions
• Checked exceptions are not runtime exceptions and
are checked by the compiler
Best Practice
 Better to declare exception than to handle
it incompetently
Checked and Unchecked Exceptions
Designing Your Own Exceptions
if (amount > balance)
throw new InsufficientFundsException();
 Make it an unchecked exception – programmer could
have avoided it by calling getBalance()
 Extend RuntimeException and supply two
constructors
public class InsufficientFundsException
extends RuntimeException {
public InsufficientFundsException(){}
public InsufficientFundsException (String msg){
super(reason);
}
}
Example
 Program
• reads coin descriptions from file
• adds coins to purse
• prints total
 What can go wrong?
• File might not exist
• File might have data in wrong format
 Who can detect the faults?
• main method of PurseTest interacts with user
• main method can report errors
• Other methods pass exceptions to caller
The read method of the Coin class
 Distinguishes between expected and unexpected end of
file
public boolean read(BufferedReader in)
throws IOException {
String input =in.readLine();
if (input == null) // normal end of file
return false;
value = Double.parseDouble(input);
//may throw unchecked NumberFormatException
name = in.readLine();
if (name == null) // unexpected end of file
throw new EOFException("Coin name
expected");
return true;
}
The read method of the Purse class
 Unconcerned with exceptions
 Just passes them to caller
public void read(BufferedReader in)
throws IOException {
boolean done = false;
while (! done) {
Coin c = new Coin();
if (c.read(in)) {
add(c);
} else {
done =true;
}
}
}
The readFile method of the Purse class
 finally clause closes files if exception happens
public void readFile(String filename)
throws IOException {
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(filename));
read(in);
} finally {
if (in != null)
in.close();
}
}
User interaction in main
 If an exception occurs, user can specify another file
name
boolean done = false;
String filename = args[0];
while (!done) {
try {
Purse myPurse = new Purse();
myPurse.readFile(filename);
System.out.println (
"total="+ myPurse.getTotal());
done = true;
} catch (IOException exception) {
System.out.println(
"Input/output error " + exception);
} catch (NumberFormatException exception) {
// error in file format
exception.printStackTrace();
}
Scenario
 PurseTest.main calls Purse.readFile
 Purse.readFile calls Purse.read
 Purse.read calls Coin.read
 Coin.read throws an EOFException
 Coin.read has no handler for the exception and
terminates immediately.
 Purse.read has no handler for the exception and
terminates immediately
 Purse.readFile has no handler for the exception and
terminates immediately after executing the finally
clause and closing the file.
 PurseTest.main has a handler for an IOException ,
a superclass of EOFException. That handler prints a
message to the user.
24
When to do what?
 If code that your code calls declares that it
can throw an Exception, what should you
do?
• Just throw the exception
• Catch the exception, report it, and recover
• Catch the exception, make a new, different
exception, and throw the new one
 When do you throw an Exception even if
no Exception was thrown to you?
25
When to re-throw the Exception
 If it’s more appropriate to deal with it at a
higher level of the code.
 If the exception means death to the
method it’s in. In other words, there’s no
reasonable way you can continue to
execute the code of this method.
26
When to catch it and recover
 If this is the appropriate place to report the
exception to the user, or log it, or whatever
you plan to do with it.
 If you can and should continue with this
method – for example if you can use a
default value, or try again.
27
When to catch it & throw your own
 If you’re sure the Exception is impossible
(your code is correct), so you don’t want to
have to declare it all the way up.
 On the other hand, if your code is
incorrect, you should not “hide” the
exception – you need to see it so that you
can fix your programmer error. Throw a
new RuntimeException, or your own sub
class of RunTimeException.
28
When to create your own Exception
 Sometimes you might create a new
Exception instance even though none of
your code threw one to you. You might be
the first “thrower” of this Exception.
 You should do this if your code detects
some error state that you cannot recover
from in this method – for example, an input
might be of an illegal value.
29
Use of Exceptions
 When handling critical events that may
jeopardize the system stability or worse.
• Obvious
 Feedback to the caller
• Should we throw an Exception when the user
inputs data with wrong syntax?
• What’s your point of view?
• Depends on the context?
• Is the fine line fuzzy and gray again?
30
Checked or Unchecked?
 If you create your own new Exception class, should it be
checked or Runtime?
 RuntimeExceptions are for programmer error
• i.e. your code is in a bad state. Stop program execution and go
debug. By the time a program reaches an end-user, it should never
throw these. The outermost layer of your program should gracefully
catch all Exceptions, even Runtimes and do something user-
friendly.
 Checked exceptions (all except RuntimeExceptions) are
for dealing with the outside world.
• If something about the input the user gave you is bad, or a file is
corrupt, or a database server is down, these are real-life things that
could happen, and your program should cope with them as
gracefully as possible.
31
Summary of Exceptions
 Catch and hide an exception if
• Can recover: (default value, user try again)
 Re-throw an exception if
• Irrecoverable to method
• More appropriate to handle elsewhere
 Throw new if
• You receive a checked exception and want to
throw an unchecked runtime exception
32
Summary of Exceptions
 When creating your own exception class
• Name it descriptively
• Place appropriately in class heirarchy
• If programmer error, make it a subclass of
RuntimeException (so it’s unchecked)
• If outside error (network, user, etc.), make it a
checked Exception
Thank You
Ad

More Related Content

Similar to Exception Handling.ppt (20)

Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
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
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling.pptxnn h
Exception handling.pptxnn                                        hException handling.pptxnn                                        h
Exception handling.pptxnn h
sabarivelan111007
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptxpresentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptxpresentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Exception and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .pptException and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .ppt
JyothiAmpally
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia
 
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Java Exceptions
Java ExceptionsJava Exceptions
Java Exceptions
jalinder123
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
DrRajeshreeKhande
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Javaexceptions
JavaexceptionsJavaexceptions
Javaexceptions
parthu310
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
Arjun Shanka
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
Pawan Kumar
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
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
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
presentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptxpresentation-on-exception-handling-160611180456 (1).pptx
presentation-on-exception-handling-160611180456 (1).pptx
ArunPatrick2
 
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptxpresentation-on-exception-handling 1.pptx
presentation-on-exception-handling 1.pptx
ArunPatrickK1
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Exception and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .pptException and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .ppt
JyothiAmpally
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Javaexceptions
JavaexceptionsJavaexceptions
Javaexceptions
parthu310
 

Recently uploaded (20)

Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Ad

Exception Handling.ppt

  • 2. Goals  To learn how to throw exceptions  To be able to design your own exception classes  To understand the difference between checked and unchecked exceptions  To learn how to catch exceptions  To know when and where to catch an exception
  • 3. Separating Error Handling Code  Traditional approach to error handling: method returns error code readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }  What happens if the file can't be opened? the length of the file can't be determined? enough memory can't be allocated? if the read fails? if the file can't be closed?  To answer, you'd have to add a lot of code to do error detection, reporting and handling
  • 4. Separating Error Handling Code errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }
  • 5. The Alternative: Exception Handling  Exceptions enable to write the main flow of code and deal with the, well, exceptional cases elsewhere readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } }
  • 6. Propagating Errors Up the Call Stack  Exceptions enable you to propagate error reporting up the call stack of methods method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; }
  • 7. Propagating Errors Up the Call Stack  The Java runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }
  • 8. Grouping Error Types and Error Differentiation  Exceptions fall into categories or groups.
  • 9. Using Exceptions  The throw clause • Exceptions originate within a method or block of code using the throw clause throw someThrowableObject;  The throws clause • Specifies that the method can throw Exception(s) public Object pop() throws EmptyStackException {}
  • 10. Using Exceptions  The try block • is used to wrap or enclose code where exceptions may occur  The catch block • A method can catch an exception by providing an exception handler for that type of exception • Typically, a catch block is created for each type of exception that can occur.
  • 11. The finally Clause  Exception terminates current method  Danger: Can skip over essential code BufferedReader in = new BufferedReader( new FileReader(filename)); purse.read(in); in.close();  Must execute in.close() even if exception happens  Use finally clause for code that must be executed "no matter what"
  • 12. Example: Catching Exceptions public void openAfile() { try { // Next two lines may generate an exception. BufferedReader br = new BufferedReader( new FileReader ("aFile.txt")); String s = br.readLine(); br.close(); // If no exceptions occur the following line // will be executed. System.out.println ("open File returned normally"); } catch (FileNotFoundException e) { System.out.println ("Cannot find file to open!"); } catch (IOException e) { System.out.println ("IOException: " + e); } finally { try { if (br != null) br.close(); } catch (IOException e) { }; } }
  • 13. Example: Declaring Exceptions public static void main (String args[]) { try { openAfile(); } catch (FileNotFoundException e) { System.out.println ("Cannot find file to open!"); } catch (IOException e) { System.out.println ("IOException: " + e); } } public static void openAfile() throws FileNotFoundException, IOException { // Next two lines may generate an exception. BufferedReader br = new BufferedReader( new FileReader("aFile.txt")); String s = br.readLine(); br.close(); System.out.println("openAFile returned normally"); }
  • 14. Exception Specification  Java exceptions are of different types including I/O Exceptions, runtime exceptions, and exceptions of your own creation • Runtime exceptions occur within the JRE, includes: arithmetic exceptions, pointer exceptions, and indexing exceptions • The compiler does not require that you catch or specify runtime exceptions • Checked exceptions are not runtime exceptions and are checked by the compiler
  • 15. Best Practice  Better to declare exception than to handle it incompetently
  • 16. Checked and Unchecked Exceptions
  • 17. Designing Your Own Exceptions if (amount > balance) throw new InsufficientFundsException();  Make it an unchecked exception – programmer could have avoided it by calling getBalance()  Extend RuntimeException and supply two constructors public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException(){} public InsufficientFundsException (String msg){ super(reason); } }
  • 18. Example  Program • reads coin descriptions from file • adds coins to purse • prints total  What can go wrong? • File might not exist • File might have data in wrong format  Who can detect the faults? • main method of PurseTest interacts with user • main method can report errors • Other methods pass exceptions to caller
  • 19. The read method of the Coin class  Distinguishes between expected and unexpected end of file public boolean read(BufferedReader in) throws IOException { String input =in.readLine(); if (input == null) // normal end of file return false; value = Double.parseDouble(input); //may throw unchecked NumberFormatException name = in.readLine(); if (name == null) // unexpected end of file throw new EOFException("Coin name expected"); return true; }
  • 20. The read method of the Purse class  Unconcerned with exceptions  Just passes them to caller public void read(BufferedReader in) throws IOException { boolean done = false; while (! done) { Coin c = new Coin(); if (c.read(in)) { add(c); } else { done =true; } } }
  • 21. The readFile method of the Purse class  finally clause closes files if exception happens public void readFile(String filename) throws IOException { BufferedReader in = null; try { in = new BufferedReader( new FileReader(filename)); read(in); } finally { if (in != null) in.close(); } }
  • 22. User interaction in main  If an exception occurs, user can specify another file name boolean done = false; String filename = args[0]; while (!done) { try { Purse myPurse = new Purse(); myPurse.readFile(filename); System.out.println ( "total="+ myPurse.getTotal()); done = true; } catch (IOException exception) { System.out.println( "Input/output error " + exception); } catch (NumberFormatException exception) { // error in file format exception.printStackTrace(); }
  • 23. Scenario  PurseTest.main calls Purse.readFile  Purse.readFile calls Purse.read  Purse.read calls Coin.read  Coin.read throws an EOFException  Coin.read has no handler for the exception and terminates immediately.  Purse.read has no handler for the exception and terminates immediately  Purse.readFile has no handler for the exception and terminates immediately after executing the finally clause and closing the file.  PurseTest.main has a handler for an IOException , a superclass of EOFException. That handler prints a message to the user.
  • 24. 24 When to do what?  If code that your code calls declares that it can throw an Exception, what should you do? • Just throw the exception • Catch the exception, report it, and recover • Catch the exception, make a new, different exception, and throw the new one  When do you throw an Exception even if no Exception was thrown to you?
  • 25. 25 When to re-throw the Exception  If it’s more appropriate to deal with it at a higher level of the code.  If the exception means death to the method it’s in. In other words, there’s no reasonable way you can continue to execute the code of this method.
  • 26. 26 When to catch it and recover  If this is the appropriate place to report the exception to the user, or log it, or whatever you plan to do with it.  If you can and should continue with this method – for example if you can use a default value, or try again.
  • 27. 27 When to catch it & throw your own  If you’re sure the Exception is impossible (your code is correct), so you don’t want to have to declare it all the way up.  On the other hand, if your code is incorrect, you should not “hide” the exception – you need to see it so that you can fix your programmer error. Throw a new RuntimeException, or your own sub class of RunTimeException.
  • 28. 28 When to create your own Exception  Sometimes you might create a new Exception instance even though none of your code threw one to you. You might be the first “thrower” of this Exception.  You should do this if your code detects some error state that you cannot recover from in this method – for example, an input might be of an illegal value.
  • 29. 29 Use of Exceptions  When handling critical events that may jeopardize the system stability or worse. • Obvious  Feedback to the caller • Should we throw an Exception when the user inputs data with wrong syntax? • What’s your point of view? • Depends on the context? • Is the fine line fuzzy and gray again?
  • 30. 30 Checked or Unchecked?  If you create your own new Exception class, should it be checked or Runtime?  RuntimeExceptions are for programmer error • i.e. your code is in a bad state. Stop program execution and go debug. By the time a program reaches an end-user, it should never throw these. The outermost layer of your program should gracefully catch all Exceptions, even Runtimes and do something user- friendly.  Checked exceptions (all except RuntimeExceptions) are for dealing with the outside world. • If something about the input the user gave you is bad, or a file is corrupt, or a database server is down, these are real-life things that could happen, and your program should cope with them as gracefully as possible.
  • 31. 31 Summary of Exceptions  Catch and hide an exception if • Can recover: (default value, user try again)  Re-throw an exception if • Irrecoverable to method • More appropriate to handle elsewhere  Throw new if • You receive a checked exception and want to throw an unchecked runtime exception
  • 32. 32 Summary of Exceptions  When creating your own exception class • Name it descriptively • Place appropriately in class heirarchy • If programmer error, make it a subclass of RuntimeException (so it’s unchecked) • If outside error (network, user, etc.), make it a checked Exception