SlideShare a Scribd company logo
1 of 34
Java Exception Handling
Outline
What exceptions are for
What exceptions are NOT for
Catching & Throwing exceptions
Exception Specifications
Standard Java Exceptions
The finally clause
Uncaught Exceptions
What Exceptions are For
To handle Bad Things
 I/O errors, other runtime errors
 when a function fails to fulfill its specification
 so you can restore program stability (or exit
gracefully)
What Exceptions are For
~ continued ~
To force you to handle Bad Things
 because return codes can be tedious
 and sometimes you’re lazy
To signal errors from constructors
 because constructors have no return value
Example
File I/O
public FileReader(String fileName)
throws FileNotFoundException
public void close() throws IOException
import java.io.*;
class OpenFile
{
public static void main(String[] args)
{
if (args.length > 0)
{
try
{
// Open a file:
FileReader f =
new FileReader(args[0]);
System.out.println(args[0]
+ " opened");
f.close();
}
catch (IOException x)
{
System.out.println(x);
}
}
}
}
What Exceptions are NOT For
NOT For Alternate Returns:
 e.g., when end-of-file is reached:
while ((s = f.readLine()) != null) …
Exceptions are only for the exceptional!
Catching Exceptions
Wrap code to be checked in a try-block
 checking occurs all the way down the execution
stack
try-blocks can be nested
 control resumes at most enclosed matching
handler
Working of try-catch
try block
Statement that causes
an exception
Catch block
Statement that
handles the
exception
Throws exception
object
Exception object creator
Exception handler
Catching Exceptions
~ continued ~
Place one or more catch-clauses after try-
block
 runtime system looks back up the call stack for
a matching handler
 subclass types match superclass types
 catching Exception catches everything (almost)
 handlers are checked in the order they appear
 place most derived types first!
 execution resumes after last handler
 if you let it (could branch or throw)
Multiple catch statements
syntax:
Try
{
Statement; //generates an exception
}
Catch(Exception type1 e)
{Statement;}
Catch(Exception type2 e1)
{Statement;}
……..
…….
Throwing Exceptions
Must throw objects derived (ultimately) from
Throwable
Usually derive from java.lang.Exception
The class name is the most important attribute of
an exception
Can optionally include a message
 Provide two constructors:
 MyException( )
 MyException(String s)
Throwing Exceptions
~ continued ~
Control is passed up the execution stack to
a matching handler
Various methods exist for processing
exceptions:
 getMessage( )
 toString( ) (class name + message)
 printStackTrace( )
Throwing Exceptions
~ continued ~
Functions must “advertise” their exceptions
 every function must specify the “checked”
exceptions it (or its callees!) may throw
Callers must do one of two things:
 handle your exceptions with try-catch, or
 advertise your exceptions along with theirs
Standard Java Exceptions
Throwable
Exception Error
RuntimeException IOException . . .
Class java.lang.Exception
The one you usually derive from
“Checked Exceptions”
 specifications checked at compile time
 you must either catch or advertise these
 Used for recoverable errors
 Not programmer errors
java.lang.Exception Subclasses
~ sample ~
AWTException
ClassNotFoundException
CloneNotSupportedException
IOException
NoSuchFieldException
Class java.lang.Error
For JVM Failures and other Weird Things
 let program terminate
InternalError is one of these
Don’t catch them
 you don’t know what to do!
These are “unchecked exceptions”
 not required to advertise
java.lang.Error Subclasses
AWTError
LinkageError
 …
ThreadDeath
VirtualMachineError
 InternalError, OutOfMemoryError,
StackOverflowError, UnknownError
Class java.lang.RuntimeException
Stupid Name!
 Same as logic_error in C++
Program logic errors
 e.g., bad cast, using a null handle, array index
violation, etc.
 Shouldn’t happen!
 fixed during testing
 Similar in spirit to C’s assert( ) macro
 mainly for debugging
These are called “unchecked exceptions”
java.lang.RuntimeException
Subclasses (sample)
ArithmeticException (e.g., divide by 0)
ArrayStoreException
ClassCastException
IllegalArgumentException
IndexOutOfBoundsException
NullPointerException
UnsupportedOperationException
The finally Clause
For code that must ALWAYS run
 No matter what!
 Even if a return or break occurs first
 Exception: System.exit( )
Placed after handlers (if they exist)
 try-block must either have a handler or a
finally-block
The finally Clause
~ continued ~
 The finally can be used to handle an exception (ie) not caught by any of the
previous catch statement.
 Finally block can be used to handle any exception generated within a try
block.
 It may be added immediately after the try block or after the last catch block.
Syntax:
try{ try{
…..} …..}
finally{ catch(…){
……} …..}
finally{
……}
Exception-handling Syntax
~ The Whole Picture ~
try
{
// normal code (conditionally executes)
}
catch (ExceptionType1 x)
{
// handle ExceptionType1 error
}
…
catch (ExceptionTypeN x)
{
// handle ExceptionTypeN error
}
finally
{
// invariant code ("always" executes)
}
class FinallyTest
{
public static void f()
throws Exception
{
try
{
// 0
// return; // 1
// System.exit(0); // 2
// throw new Exception(); // 3a
}
catch (Exception x)
{
// throw new Exception(); // 3b
}
finally
{
System.out.println("finally!");
}
System.out.println("last statement");
}
public static void main(String[] args)
{
try
{
f();
}
catch(Exception x)
{}
}
}
Program Output
0:
finally!
last statement
1:
finally!
2:
(no output)
3a:
same as 0:
3a + 3b:
compiler error (last statement not reachable)
When to Handle Exceptions
Note: Manage.f( ) didn’t catch anything
 wouldn’t know what to do if it did!
You often let exceptions pass up the call
stack
Or you can re-throw in a catch
 throw x; // in a handler where x was caught
 or re-throw a new type of exception
Exception Etiquette
Don’t catch what you can’t (at least
partially) handle
 re-throw if only partially handled (“catch &
release”: if you’re not going to eat it, throw it
back!)
Don’t catch & ignore
 catch (Exception x){} // disables exceptions!
How Exceptions Work
When an exception is thrown execution
backtracks up the runtime stack (list of active
function invocations)
Each stack frame contains information regarding
local handlers, if any
 Otherwise, execution returns up to the next caller,
looking for a suitable catch
What happens if there isn’t a matching catch?
Uncaught Exceptions
What if there is no handler for an
exception?
The thread dies!
 exceptions belong to a thread (stack-specific)
Throwing our own Exceptions
Syntax:
Throw new throwable_subclass;
Ex:
Throw new Arithmetic Exception();
Program
import java.lang.Exception;
class my extends Exception {
my(String msg);}
class test
{ public static void main(String a[])
{ int x=5,y=1000;
try {float z=(float) x / (float) y;
if(z<0.01)
{ throw new my(“Number is to small”); }
}
Catch(my e)
{ S.o.p(“Caught my exception”);
S.o.p(“e.getMessage()); }
~ continued ~
Finally
{ S.o.p(“I am always here”);
} } }
O/P:
Caught my exception
Number is to small
I am always here

More Related Content

What's hot

Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and AppletsTanmoy Roy
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVAKunal Singh
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaManav Prasad
 
Exceptions
ExceptionsExceptions
Exceptionsmotthu18
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaRajkattamuri
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Edureka!
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in JavaQaziUmarF786
 

What's hot (20)

Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
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
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
3.C#
3.C#3.C#
3.C#
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception
ExceptionException
Exception
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 

Similar to JavaExceptionHandling

Similar to JavaExceptionHandling (20)

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
exception handling
exception handlingexception handling
exception handling
 
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
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Unit5 java
Unit5 javaUnit5 java
Unit5 java
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
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
 

More from Abishek Purushothaman

More from Abishek Purushothaman (8)

Aws solution architect
Aws solution architectAws solution architect
Aws solution architect
 
Machine learning
Machine learningMachine learning
Machine learning
 
Multiple choice questions for Java io,files and inheritance
Multiple choice questions for Java io,files and inheritanceMultiple choice questions for Java io,files and inheritance
Multiple choice questions for Java io,files and inheritance
 
Multiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingMultiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handling
 
Introduction to R for beginners
Introduction to R for beginnersIntroduction to R for beginners
Introduction to R for beginners
 
Mini Project presentation for MCA
Mini Project presentation for MCAMini Project presentation for MCA
Mini Project presentation for MCA
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 

Recently uploaded

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Recently uploaded (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

JavaExceptionHandling

  • 2. Outline What exceptions are for What exceptions are NOT for Catching & Throwing exceptions Exception Specifications Standard Java Exceptions The finally clause Uncaught Exceptions
  • 3. What Exceptions are For To handle Bad Things  I/O errors, other runtime errors  when a function fails to fulfill its specification  so you can restore program stability (or exit gracefully)
  • 4. What Exceptions are For ~ continued ~ To force you to handle Bad Things  because return codes can be tedious  and sometimes you’re lazy To signal errors from constructors  because constructors have no return value
  • 5. Example File I/O public FileReader(String fileName) throws FileNotFoundException public void close() throws IOException
  • 6. import java.io.*; class OpenFile { public static void main(String[] args) { if (args.length > 0) { try { // Open a file: FileReader f = new FileReader(args[0]); System.out.println(args[0] + " opened"); f.close(); } catch (IOException x) { System.out.println(x); } } } }
  • 7. What Exceptions are NOT For NOT For Alternate Returns:  e.g., when end-of-file is reached: while ((s = f.readLine()) != null) … Exceptions are only for the exceptional!
  • 8. Catching Exceptions Wrap code to be checked in a try-block  checking occurs all the way down the execution stack try-blocks can be nested  control resumes at most enclosed matching handler
  • 9. Working of try-catch try block Statement that causes an exception Catch block Statement that handles the exception Throws exception object Exception object creator Exception handler
  • 10. Catching Exceptions ~ continued ~ Place one or more catch-clauses after try- block  runtime system looks back up the call stack for a matching handler  subclass types match superclass types  catching Exception catches everything (almost)  handlers are checked in the order they appear  place most derived types first!  execution resumes after last handler  if you let it (could branch or throw)
  • 11. Multiple catch statements syntax: Try { Statement; //generates an exception } Catch(Exception type1 e) {Statement;} Catch(Exception type2 e1) {Statement;} …….. …….
  • 12. Throwing Exceptions Must throw objects derived (ultimately) from Throwable Usually derive from java.lang.Exception The class name is the most important attribute of an exception Can optionally include a message  Provide two constructors:  MyException( )  MyException(String s)
  • 13. Throwing Exceptions ~ continued ~ Control is passed up the execution stack to a matching handler Various methods exist for processing exceptions:  getMessage( )  toString( ) (class name + message)  printStackTrace( )
  • 14. Throwing Exceptions ~ continued ~ Functions must “advertise” their exceptions  every function must specify the “checked” exceptions it (or its callees!) may throw Callers must do one of two things:  handle your exceptions with try-catch, or  advertise your exceptions along with theirs
  • 15. Standard Java Exceptions Throwable Exception Error RuntimeException IOException . . .
  • 16. Class java.lang.Exception The one you usually derive from “Checked Exceptions”  specifications checked at compile time  you must either catch or advertise these  Used for recoverable errors  Not programmer errors
  • 17. java.lang.Exception Subclasses ~ sample ~ AWTException ClassNotFoundException CloneNotSupportedException IOException NoSuchFieldException
  • 18. Class java.lang.Error For JVM Failures and other Weird Things  let program terminate InternalError is one of these Don’t catch them  you don’t know what to do! These are “unchecked exceptions”  not required to advertise
  • 19. java.lang.Error Subclasses AWTError LinkageError  … ThreadDeath VirtualMachineError  InternalError, OutOfMemoryError, StackOverflowError, UnknownError
  • 20. Class java.lang.RuntimeException Stupid Name!  Same as logic_error in C++ Program logic errors  e.g., bad cast, using a null handle, array index violation, etc.  Shouldn’t happen!  fixed during testing  Similar in spirit to C’s assert( ) macro  mainly for debugging These are called “unchecked exceptions”
  • 21. java.lang.RuntimeException Subclasses (sample) ArithmeticException (e.g., divide by 0) ArrayStoreException ClassCastException IllegalArgumentException IndexOutOfBoundsException NullPointerException UnsupportedOperationException
  • 22. The finally Clause For code that must ALWAYS run  No matter what!  Even if a return or break occurs first  Exception: System.exit( ) Placed after handlers (if they exist)  try-block must either have a handler or a finally-block
  • 23. The finally Clause ~ continued ~  The finally can be used to handle an exception (ie) not caught by any of the previous catch statement.  Finally block can be used to handle any exception generated within a try block.  It may be added immediately after the try block or after the last catch block. Syntax: try{ try{ …..} …..} finally{ catch(…){ ……} …..} finally{ ……}
  • 24. Exception-handling Syntax ~ The Whole Picture ~ try { // normal code (conditionally executes) } catch (ExceptionType1 x) { // handle ExceptionType1 error } … catch (ExceptionTypeN x) { // handle ExceptionTypeN error } finally { // invariant code ("always" executes) }
  • 25. class FinallyTest { public static void f() throws Exception { try { // 0 // return; // 1 // System.exit(0); // 2 // throw new Exception(); // 3a } catch (Exception x) { // throw new Exception(); // 3b } finally { System.out.println("finally!"); } System.out.println("last statement"); }
  • 26. public static void main(String[] args) { try { f(); } catch(Exception x) {} } }
  • 27. Program Output 0: finally! last statement 1: finally! 2: (no output) 3a: same as 0: 3a + 3b: compiler error (last statement not reachable)
  • 28. When to Handle Exceptions Note: Manage.f( ) didn’t catch anything  wouldn’t know what to do if it did! You often let exceptions pass up the call stack Or you can re-throw in a catch  throw x; // in a handler where x was caught  or re-throw a new type of exception
  • 29. Exception Etiquette Don’t catch what you can’t (at least partially) handle  re-throw if only partially handled (“catch & release”: if you’re not going to eat it, throw it back!) Don’t catch & ignore  catch (Exception x){} // disables exceptions!
  • 30. How Exceptions Work When an exception is thrown execution backtracks up the runtime stack (list of active function invocations) Each stack frame contains information regarding local handlers, if any  Otherwise, execution returns up to the next caller, looking for a suitable catch What happens if there isn’t a matching catch?
  • 31. Uncaught Exceptions What if there is no handler for an exception? The thread dies!  exceptions belong to a thread (stack-specific)
  • 32. Throwing our own Exceptions Syntax: Throw new throwable_subclass; Ex: Throw new Arithmetic Exception();
  • 33. Program import java.lang.Exception; class my extends Exception { my(String msg);} class test { public static void main(String a[]) { int x=5,y=1000; try {float z=(float) x / (float) y; if(z<0.01) { throw new my(“Number is to small”); } } Catch(my e) { S.o.p(“Caught my exception”); S.o.p(“e.getMessage()); }
  • 34. ~ continued ~ Finally { S.o.p(“I am always here”); } } } O/P: Caught my exception Number is to small I am always here

Editor's Notes

  1. Throwable is a class.
  2. Errors can be caught, but shouldn’t be.