SlideShare a Scribd company logo
1 of 28
Exception Handling
Chapter 15
2
What You Will Learn
Use
try,
throw,
catch
to
watch for
indicate exceptions
handle
How to process exceptions and failures.
3
Motivation
 We seek robust programs
 When something unexpected occurs
 Ensure program detects the problem
 Then program must do something about it
 Extensive testing of special situations can result in
"spaghetti code"
 Need mechanism to check for problem where it
could occur
 When condition does occur
 Have control passed to code to handle the problem
4
Overview
 Exception
 Indication of problem during execution
 Uses of exception handling
 Process exceptions from program components
 Handle exceptions in a uniform manner in large projects
 Remove error-handling code from “main line” of
execution
 A method detects an error and throws an
exception
 Exception handler processes the error
 Uncaught exceptions yield adverse effects
 Might terminate program execution
5
Overview
 Code that could generate errors put in try
blocks
 Code for error handling enclosed in a catch
clause
 The finally clause always executes
 Termination model of exception handling
 The block in which the exception occurs expires
 throws clause specifies exceptions
method throws
6
Exception Handler
Exception
"thrown" here
Exception
handler
Exception
handler
Thrown exception matched against
first set of exception handlers
If it fails to match, it is matched against
next set of handlers, etc.
If exception matches none of handlers,
program is abandoned
7
Terminology
 Thrown exception – an exception that has occurred
 Stack trace
 Name of the exception in a descriptive message that
indicates the problem
 Complete method-call stack
 ArithmeticException – can arise from a
number of different problems in arithmetic
8
Terminology
 Throw point – initial point at which the
exception occurs, top row of call chain
 InputMismatchException – occurs
when Scanner method nextInt receives
a string that does not represent a valid
integer
 See Example, Figure 13.1
9
Termination Model of
Exception Handling
 When an exception occurs:
 try block terminates immediately
 Program control transfers to first matching catch
block
 try statement – consists of try block and
corresponding catch and/or finally blocks
10
Contrast
Termination model
 program control does not return to the throw
point
 try block has expired;
 Flow of control proceeds to the first statement
after the last catch block
Resumption model
 program control resumes just after throw point
11
Enclosing Code in a try
Block
try block – encloses code that might throw
an exception and the code that should not
execute if an exception occurs
Consists of keyword try followed by a block
of code enclosed in curly braces
12
Using the throws Clause
Appears after method’s parameter list and
before the method’s body
Contains a comma-separated list of
exceptions
13
Using the throws Clause
Exceptions can be thrown by statements in
method’s body of by methods called in
method’s body
Exceptions can be of types listed in throws
clause or subclasses
14
Example: Handling
ArithmeticExceptions and
InputMismatchExceptions
With exception handling
 program catches and handles the exception
Example, Figure 13.2
 Allows user to try again if invalid input is
entered (zero for denominator, or non-integer
input)
15
Sequence of Events for
throw
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
16
Sequence of Events for
No throw
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
17
When to Use Exception
Handling
Exception handling designed to process
synchronous errors
 Synchronous errors – occur when a statement
executes
 Asynchronous errors – occur in parallel with
and independent of the program’s flow of
control
Avoid using exception handling as an
alternate form of flow of control.
18
Java Exception Hierarchy
 Superclass Throwable
 Subclass Exception
 Exceptional situations
 Should be caught by program
 Subclass Error
 Typically not caught by program
 Checked exceptions
 Catch or declare
 Unchecked exceptions
19
Java Exception Hierarchy
All exceptions inherit either directly or
indirectly from class Exception
Exception classes form an inheritance
hierarchy that can be extended
20
Java Exception Hierarchy
 Class Throwable, superclass of Exception
 Only Throwable objects can be used with the
exception-handling mechanism
 Has two subclasses: Exception and Error
 Class Exception and its subclasses represent
exception situations that can occur in a Java program
and that can be caught by the application
 Class Error and its subclasses represent abnormal
situations that could happen in the JVM – it is usually
not possible for a program to recover from Errors
21
Inheritance hierarchy for
class Throwable
22
Checked Exceptions
 Inherit from class Exception but not from
RuntimeException
 Compiler enforces catch-or-declare requirement
 Compiler checks each method call and method
declaration
 determines whether method throws checked
exceptions.
 If so, the compiler ensures checked exception caught
or declared in throws clause.
 If not caught or declared, compiler error occurs.
23
Unchecked Exceptions
 Inherit from class RuntimeException or class
Error
 Compiler does not check code to see if
exception caught or declared
 If an unchecked exception occurs and not caught
 Program terminates or runs with unexpected results
 Can typically be prevented by proper coding
24
Java Exception Hierarchy
catch block catches all exceptions of its
type and subclasses of its type
If there are multiple catch blocks that match
a particular exception type, only the first
matching catch block executes
Makes sense to use a catch block of a
superclass when all catch blocks for that
class’s subclasses will perform same
functionality
25
finally Block
Consists of finally keyword followed by
a block of code enclosed in curly braces
Optional in a try statement
If present, is placed after the last catch
block
View position, Figure 13.4
26
finally Block
Executes whether or not an exception is
thrown in the corresponding try block or
any of its corresponding catch blocks
Will not execute if the application exits early
from a try block via method
System.exit
Typically contains resource-release code
27
Using finally
 View program, Figure 13.5
 Note
 Re-throw of exception
 Code for throw exception
 Blocks using finally
 Suggestion
 Do not use a try block for every individual
statement which may cause a problem
 Enclose groups of statements
 Follow by multiple catch blocks
28
Sequence of Events for
finally clause
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
finally

More Related Content

What's hot

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
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 handlingKuntal Bhowmick
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1sotlsoc
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in javaSameer Patil
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 

What's hot (13)

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Introduction to Exception
Introduction to ExceptionIntroduction to Exception
Introduction to Exception
 
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
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
summarizer16fev16_Exceptions
summarizer16fev16_Exceptionssummarizer16fev16_Exceptions
summarizer16fev16_Exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 

Viewers also liked

اعتماد مهندس المشروع.pdf2
اعتماد مهندس المشروع.pdf2اعتماد مهندس المشروع.pdf2
اعتماد مهندس المشروع.pdf2Yousef Younis
 
Caribbean christmas.key
Caribbean christmas.keyCaribbean christmas.key
Caribbean christmas.keykennprop
 
Microsoft Project - مستندات
Microsoft Project - مستنداتMicrosoft Project - مستندات
Microsoft Project - مستنداتYousef Younis
 
Aplicación de conceptos de Joan Costa
Aplicación de conceptos de Joan CostaAplicación de conceptos de Joan Costa
Aplicación de conceptos de Joan Costaúltima cena
 
Poemario de Christian Madera
Poemario de Christian MaderaPoemario de Christian Madera
Poemario de Christian MaderaMaestra Dámaris
 
Waterpilot FMX167 Endress+Hauser
Waterpilot FMX167 Endress+HauserWaterpilot FMX167 Endress+Hauser
Waterpilot FMX167 Endress+HauserArve
 
Whole Foods Market in Singapore
Whole Foods Market in SingaporeWhole Foods Market in Singapore
Whole Foods Market in SingaporeAngel Kim
 
OptiCall Webinar: Give Patients a Reason to Say "Yes"
OptiCall Webinar:  Give Patients a Reason to Say "Yes"OptiCall Webinar:  Give Patients a Reason to Say "Yes"
OptiCall Webinar: Give Patients a Reason to Say "Yes"OptiCall
 
Evaluacion, diagnistico, pronostico, categorias
Evaluacion, diagnistico, pronostico, categoriasEvaluacion, diagnistico, pronostico, categorias
Evaluacion, diagnistico, pronostico, categoriasIrene Pringle
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Simone de Beavouir-Oussama i Manel
Simone de Beavouir-Oussama i ManelSimone de Beavouir-Oussama i Manel
Simone de Beavouir-Oussama i ManelOussama Kadiri
 

Viewers also liked (19)

Vectorização
VectorizaçãoVectorização
Vectorização
 
Presentación de etica
Presentación de eticaPresentación de etica
Presentación de etica
 
s2_2012_academic
s2_2012_academics2_2012_academic
s2_2012_academic
 
s1_2011_academic
s1_2011_academics1_2011_academic
s1_2011_academic
 
اعتماد مهندس المشروع.pdf2
اعتماد مهندس المشروع.pdf2اعتماد مهندس المشروع.pdf2
اعتماد مهندس المشروع.pdf2
 
Caribbean christmas.key
Caribbean christmas.keyCaribbean christmas.key
Caribbean christmas.key
 
Qatar 2022
Qatar 2022 Qatar 2022
Qatar 2022
 
Microsoft Project - مستندات
Microsoft Project - مستنداتMicrosoft Project - مستندات
Microsoft Project - مستندات
 
Aplicación de conceptos de Joan Costa
Aplicación de conceptos de Joan CostaAplicación de conceptos de Joan Costa
Aplicación de conceptos de Joan Costa
 
Poemario de Christian Madera
Poemario de Christian MaderaPoemario de Christian Madera
Poemario de Christian Madera
 
Waterpilot FMX167 Endress+Hauser
Waterpilot FMX167 Endress+HauserWaterpilot FMX167 Endress+Hauser
Waterpilot FMX167 Endress+Hauser
 
RVK 2016 RESUME
RVK 2016 RESUMERVK 2016 RESUME
RVK 2016 RESUME
 
Whole Foods Market in Singapore
Whole Foods Market in SingaporeWhole Foods Market in Singapore
Whole Foods Market in Singapore
 
Hypothesis
HypothesisHypothesis
Hypothesis
 
OptiCall Webinar: Give Patients a Reason to Say "Yes"
OptiCall Webinar:  Give Patients a Reason to Say "Yes"OptiCall Webinar:  Give Patients a Reason to Say "Yes"
OptiCall Webinar: Give Patients a Reason to Say "Yes"
 
Evaluacion, diagnistico, pronostico, categorias
Evaluacion, diagnistico, pronostico, categoriasEvaluacion, diagnistico, pronostico, categorias
Evaluacion, diagnistico, pronostico, categorias
 
Adjetivos y pronombres demostrativos
Adjetivos y pronombres demostrativosAdjetivos y pronombres demostrativos
Adjetivos y pronombres demostrativos
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Simone de Beavouir-Oussama i Manel
Simone de Beavouir-Oussama i ManelSimone de Beavouir-Oussama i Manel
Simone de Beavouir-Oussama i Manel
 

Similar to Chapter13 exception handling

130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.netsuraj pandey
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 

Similar to Chapter13 exception handling (20)

130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
3.C#
3.C#3.C#
3.C#
 

Chapter13 exception handling

  • 2. 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
  • 3. 3 Motivation  We seek robust programs  When something unexpected occurs  Ensure program detects the problem  Then program must do something about it  Extensive testing of special situations can result in "spaghetti code"  Need mechanism to check for problem where it could occur  When condition does occur  Have control passed to code to handle the problem
  • 4. 4 Overview  Exception  Indication of problem during execution  Uses of exception handling  Process exceptions from program components  Handle exceptions in a uniform manner in large projects  Remove error-handling code from “main line” of execution  A method detects an error and throws an exception  Exception handler processes the error  Uncaught exceptions yield adverse effects  Might terminate program execution
  • 5. 5 Overview  Code that could generate errors put in try blocks  Code for error handling enclosed in a catch clause  The finally clause always executes  Termination model of exception handling  The block in which the exception occurs expires  throws clause specifies exceptions method throws
  • 6. 6 Exception Handler Exception "thrown" here Exception handler Exception handler Thrown exception matched against first set of exception handlers If it fails to match, it is matched against next set of handlers, etc. If exception matches none of handlers, program is abandoned
  • 7. 7 Terminology  Thrown exception – an exception that has occurred  Stack trace  Name of the exception in a descriptive message that indicates the problem  Complete method-call stack  ArithmeticException – can arise from a number of different problems in arithmetic
  • 8. 8 Terminology  Throw point – initial point at which the exception occurs, top row of call chain  InputMismatchException – occurs when Scanner method nextInt receives a string that does not represent a valid integer  See Example, Figure 13.1
  • 9. 9 Termination Model of Exception Handling  When an exception occurs:  try block terminates immediately  Program control transfers to first matching catch block  try statement – consists of try block and corresponding catch and/or finally blocks
  • 10. 10 Contrast Termination model  program control does not return to the throw point  try block has expired;  Flow of control proceeds to the first statement after the last catch block Resumption model  program control resumes just after throw point
  • 11. 11 Enclosing Code in a try Block try block – encloses code that might throw an exception and the code that should not execute if an exception occurs Consists of keyword try followed by a block of code enclosed in curly braces
  • 12. 12 Using the throws Clause Appears after method’s parameter list and before the method’s body Contains a comma-separated list of exceptions
  • 13. 13 Using the throws Clause Exceptions can be thrown by statements in method’s body of by methods called in method’s body Exceptions can be of types listed in throws clause or subclasses
  • 14. 14 Example: Handling ArithmeticExceptions and InputMismatchExceptions With exception handling  program catches and handles the exception Example, Figure 13.2  Allows user to try again if invalid input is entered (zero for denominator, or non-integer input)
  • 15. 15 Sequence of Events for throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step
  • 16. 16 Sequence of Events for No throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step
  • 17. 17 When to Use Exception Handling Exception handling designed to process synchronous errors  Synchronous errors – occur when a statement executes  Asynchronous errors – occur in parallel with and independent of the program’s flow of control Avoid using exception handling as an alternate form of flow of control.
  • 18. 18 Java Exception Hierarchy  Superclass Throwable  Subclass Exception  Exceptional situations  Should be caught by program  Subclass Error  Typically not caught by program  Checked exceptions  Catch or declare  Unchecked exceptions
  • 19. 19 Java Exception Hierarchy All exceptions inherit either directly or indirectly from class Exception Exception classes form an inheritance hierarchy that can be extended
  • 20. 20 Java Exception Hierarchy  Class Throwable, superclass of Exception  Only Throwable objects can be used with the exception-handling mechanism  Has two subclasses: Exception and Error  Class Exception and its subclasses represent exception situations that can occur in a Java program and that can be caught by the application  Class Error and its subclasses represent abnormal situations that could happen in the JVM – it is usually not possible for a program to recover from Errors
  • 22. 22 Checked Exceptions  Inherit from class Exception but not from RuntimeException  Compiler enforces catch-or-declare requirement  Compiler checks each method call and method declaration  determines whether method throws checked exceptions.  If so, the compiler ensures checked exception caught or declared in throws clause.  If not caught or declared, compiler error occurs.
  • 23. 23 Unchecked Exceptions  Inherit from class RuntimeException or class Error  Compiler does not check code to see if exception caught or declared  If an unchecked exception occurs and not caught  Program terminates or runs with unexpected results  Can typically be prevented by proper coding
  • 24. 24 Java Exception Hierarchy catch block catches all exceptions of its type and subclasses of its type If there are multiple catch blocks that match a particular exception type, only the first matching catch block executes Makes sense to use a catch block of a superclass when all catch blocks for that class’s subclasses will perform same functionality
  • 25. 25 finally Block Consists of finally keyword followed by a block of code enclosed in curly braces Optional in a try statement If present, is placed after the last catch block View position, Figure 13.4
  • 26. 26 finally Block Executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks Will not execute if the application exits early from a try block via method System.exit Typically contains resource-release code
  • 27. 27 Using finally  View program, Figure 13.5  Note  Re-throw of exception  Code for throw exception  Blocks using finally  Suggestion  Do not use a try block for every individual statement which may cause a problem  Enclose groups of statements  Follow by multiple catch blocks
  • 28. 28 Sequence of Events for finally clause Preceding step try block throw statement unmatched catch matching catch unmatched catch next step finally