SlideShare uma empresa Scribd logo
1 de 73
C++ Programming:
Program Design Including
Data Structures, Third Edition
Chapter 15: Exception Handling
Objectives
In this chapter you will:

• Learn what an exception is
• Learn how to handle exceptions within a
program
• See how a try/catch block is used to
handle exceptions
• Become familiar with C++ exception classes
Objectives (continued)
• Learn how to create your own exception
classes
• Discover how to throw and rethrow an
exception
• Explore stack unwinding
Exceptions
• Exception: undesirable event detectable
during program execution
• If exceptions occurred during execution
− Programmer-supplied code terminated the
program or
− Program terminated with an appropriate error
message

• Can add exception-handling code at point
where an error can occur
Handling Exceptions within a
Program (continued)
• Function assert:
− Checks if an expression meets certain
condition(s)
− If conditions are not met, it terminates the
program

• Example: division by 0
− If divisor is zero, assert terminates the
program with an error message
Example 15-1
Example 15-2
Example 15-3
C++ Mechanisms of Exception
Handling
• The try/catch block handles exceptions
• Exception must be thrown in a try block and
caught by a catch block

• C++ provides support to handle exceptions
via a hierarchy of classes
try/catch Block
• Statements that may generate an exception
are placed in a try block
• The try block also contains statements that
should not be executed if an exception occurs
• The try block is followed by one or more
catch blocks
try/catch Block (continued)
• The catch block:
− Specifies the type of exception it can catch
− Contains an exception handler

• If the heading of a catch block contains ...
(ellipses) in place of parameters
− Catch block can catch exceptions of all
types
• General syntax of the try/catch block:
try/catch Block (continued)
• If no exception is thrown in a try block
− All catch blocks for that try block are
ignored
− Execution resumes after the last catch block

• If an exception is thrown in a try block
− Remaining statements in that try block are
ignored
try/catch Block (continued)
• The program searches catch blocks in
order, looking for an appropriate exception
handler
• If the type of thrown exception matches the
parameter type in one of the catch blocks:
− Code of that catch block executes

− Remaining catch blocks are ignored
Throwing an Exception
• For try/catch to work, the exception must
be thrown in the try block
• General syntax to throw an exception is:

where expression is a constant value,
variable, or object
Throwing an Exception (continued)
• The object being thrown can be:
− Specific object
− Anonymous object

• In C++
− An exception is a value
− throw is a reserved word
Throwing an Exception:
Order of catch Blocks
• Catch block can catch
− All exceptions of a specific type
− All types of exceptions

• A catch block with an ellipses (three dots)
catches any type of exception
• In a sequence of try/catch blocks, if the
catch block with an ellipses is needed
− It should be the last catch block of that
sequence
Using try/catch Blocks in a Program:
Example 15-6
Example 15-7
Using C++ Exception Classes
• C++ provides support to handle exceptions
via hierarchy of classes
• The function what returns the string
containing exception object thrown by C++’s
built-in exception classes
• The class exception is:
− The base class of the exception classes
provided by C++
− Contained in the header file exception
Using C++ Exception Classes
(continued)
• Two classes derived from exception:
− logic_error
− runtime_error

• logic_error and runtime_error are
defined in header file stdexcept
• The class invalid_argument deals with
illegal arguments used in a function call
Using C++ Exception Classes
(continued)
• The class out_of_range deals with the
string subscript out_of_range error
• The class length_error handles the error
if
− A length greater than the maximum allowed
for a string object is used
Using C++ Exception Classes
(continued)
• If the operator new cannot allocate memory
space
− It throws a bad_alloc exception

• The class runtime_error deals with errors
that occur only during program execution
• Classes overflow_error and
underflow_error
− Deal with arithmetic overflow and under-flow
exceptions
− Derived from the class runtime_error
Example 15-8: exceptions out_of_range and
length_error
Example 15-9: exception bad_alloc
Creating Your Own Exception
Classes
• Programmers can create exception classes to
handle exceptions not covered by C++’s
exception classes and their own exceptions
• C++ uses the same mechanism to process
the exceptions you define as for built-in
exceptions
• You must throw your own exceptions using
the throw statement
• Any class can be an exception class
Example 15-10
Example 15-11
Example 15-13
Rethrowing and Throwing an
Exception
• When an exception occurs in a try block
− Control immediately passes to one of the catch
blocks

• A catch block either
− Handles the exception or partially processes the
exception and then rethrows the same
exception OR
− Rethrows another exception for the calling
environment to handle
Rethrowing and Throwing an
Exception (continued)
• The general syntax to rethrow an exception
caught by a catch block is:

(in this case, the same exception is rethrown)
or:

where expression is a constant value,
variable, or object
Rethrowing and Throwing an
Exception (continued)
• The object being thrown can be
− A specific object
− An anonymous object

• A function specifies the exceptions it throws
in its heading using the throw clause
• A function specifies the exceptions it throws (to be handled
somewhere) in its heading using the throw clause.
• For example, the following function specifies that it throws
exceptions of type int, string, and divisionByZero,
where divisionByZero is the class as defined
previously.
Example 15-14
Exception Handling Techniques
• When an exception occurs, the programmer
usually has three choices:
− Terminate the program
− Include code to recover from the exception
− Log the error and continue
Terminate the Program
• In some cases, it is best to let the program
terminate when an exception occurs
• For example, if the input file does not exist
when the program executes
− There is no point in continuing with the
program

• The program can output an appropriate error
message and terminate
Fix the Error and Continue
• In some cases, you will want to handle the
exception and let the program continue
• For example, if a user inputs a letter in place
of a number
− The input stream will enter the fail state

• You can include the necessary code to keep
prompting the user to input a number until the
entry is valid
Log the Error and Continue
• For example, if your program is designed to
run a nuclear reactor or continuously monitor
a satellite
− It cannot be terminated if an exception occurs

• When an exception occurs
− The program should write the exception into a
file and continue to run
Example 15-16
Stack Unwinding
• When an exception is thrown in, say, a
function, the function can do the following:
− Do nothing
− Partially process the exception and throw the
same exception or a new exception
− Throw a new exception
Stack Unwinding (continued)
• In each of these cases, the function-call stack
is unwound
− The exception can be caught in the next
try/catch block

• When the function-call stack is unwound
− The function in which the exception was not
caught and/or rethrown terminates

− Memory for its local variables is destroyed
Stack Unwinding (continued)
• The stack unwinding continues until
− A try/catch handles the exception or
− The program does not handle the exception

• If the program does not handle the exception,
then the function terminate is called to
terminate the program
Example 15-17
Example 15-18
Summary
• Exception: an undesirable event detectable
during program execution
• assert checks whether an expression meets
a specified condition and terminates if not
met
• try/catch block handles exceptions
• Statements that may generate an exception
are placed in a try block
• Catch block specifies the type of exception it
can catch and contains an exception handler
Summary (continued)
• If no exceptions are thrown in a try block, all
catch blocks for that try block are ignored
and execution resumes after the last catch
block
• Data type of catch block parameter specifies
type of exception that catch block can catch
• Catch block can have at most one parameter
• exception is base class for exception classes
• what returns string containing the exception
object thrown by built-in exception classes
Summary (continued)
• Class exception is in the header file exception
• runtime_error handles runtime errors
• C++ enables programmers to create their
own exception classes
• A function specifies the exceptions it throws
in its heading using the throw clause
• If the program does not handle the exception,
then the function terminate terminates the
program

Mais conteúdo relacionado

Mais procurados

Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
Exception Handling
Exception HandlingException Handling
Exception HandlingAlpesh Oza
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]ppd1961
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++imran khan
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++Prof Ansari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaManoj_vasava
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .NetMindfire Solutions
 

Mais procurados (20)

Exception handling
Exception handlingException handling
Exception handling
 
C++ ala
C++ alaC++ ala
C++ ala
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling
Exception handlingException handling
Exception handling
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
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
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
 

Semelhante a Exception handling chapter15

9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14Terry Yoast
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptxRDeepa9
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAdil Mehmoood
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxARUNPRANESHS
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 

Semelhante a Exception handling chapter15 (20)

9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
F6dc1 session6 c++
F6dc1 session6 c++F6dc1 session6 c++
F6dc1 session6 c++
 
Javasession4
Javasession4Javasession4
Javasession4
 

Mais de Kumar

Graphics devices
Graphics devicesGraphics devices
Graphics devicesKumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithmsKumar
 
region-filling
region-fillingregion-filling
region-fillingKumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivationKumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons dericationKumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xsltKumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xmlKumar
 
Xml basics
Xml basicsXml basics
Xml basicsKumar
 
XML Schema
XML SchemaXML Schema
XML SchemaKumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xmlKumar
 
Applying xml
Applying xmlApplying xml
Applying xmlKumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLKumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee applicationKumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLKumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB FundmentalsKumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programmingKumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversKumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EEKumar
 

Mais de Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Último

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Último (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Exception handling chapter15

  • 1. C++ Programming: Program Design Including Data Structures, Third Edition Chapter 15: Exception Handling
  • 2. Objectives In this chapter you will: • Learn what an exception is • Learn how to handle exceptions within a program • See how a try/catch block is used to handle exceptions • Become familiar with C++ exception classes
  • 3. Objectives (continued) • Learn how to create your own exception classes • Discover how to throw and rethrow an exception • Explore stack unwinding
  • 4. Exceptions • Exception: undesirable event detectable during program execution • If exceptions occurred during execution − Programmer-supplied code terminated the program or − Program terminated with an appropriate error message • Can add exception-handling code at point where an error can occur
  • 5. Handling Exceptions within a Program (continued) • Function assert: − Checks if an expression meets certain condition(s) − If conditions are not met, it terminates the program • Example: division by 0 − If divisor is zero, assert terminates the program with an error message
  • 7.
  • 9.
  • 11.
  • 12. C++ Mechanisms of Exception Handling • The try/catch block handles exceptions • Exception must be thrown in a try block and caught by a catch block • C++ provides support to handle exceptions via a hierarchy of classes
  • 13. try/catch Block • Statements that may generate an exception are placed in a try block • The try block also contains statements that should not be executed if an exception occurs • The try block is followed by one or more catch blocks
  • 14. try/catch Block (continued) • The catch block: − Specifies the type of exception it can catch − Contains an exception handler • If the heading of a catch block contains ... (ellipses) in place of parameters − Catch block can catch exceptions of all types
  • 15. • General syntax of the try/catch block:
  • 16. try/catch Block (continued) • If no exception is thrown in a try block − All catch blocks for that try block are ignored − Execution resumes after the last catch block • If an exception is thrown in a try block − Remaining statements in that try block are ignored
  • 17. try/catch Block (continued) • The program searches catch blocks in order, looking for an appropriate exception handler • If the type of thrown exception matches the parameter type in one of the catch blocks: − Code of that catch block executes − Remaining catch blocks are ignored
  • 18.
  • 19. Throwing an Exception • For try/catch to work, the exception must be thrown in the try block • General syntax to throw an exception is: where expression is a constant value, variable, or object
  • 20. Throwing an Exception (continued) • The object being thrown can be: − Specific object − Anonymous object • In C++ − An exception is a value − throw is a reserved word
  • 22. Order of catch Blocks • Catch block can catch − All exceptions of a specific type − All types of exceptions • A catch block with an ellipses (three dots) catches any type of exception • In a sequence of try/catch blocks, if the catch block with an ellipses is needed − It should be the last catch block of that sequence
  • 23. Using try/catch Blocks in a Program:
  • 24.
  • 26.
  • 28.
  • 29.
  • 30. Using C++ Exception Classes • C++ provides support to handle exceptions via hierarchy of classes • The function what returns the string containing exception object thrown by C++’s built-in exception classes • The class exception is: − The base class of the exception classes provided by C++ − Contained in the header file exception
  • 31. Using C++ Exception Classes (continued) • Two classes derived from exception: − logic_error − runtime_error • logic_error and runtime_error are defined in header file stdexcept • The class invalid_argument deals with illegal arguments used in a function call
  • 32. Using C++ Exception Classes (continued) • The class out_of_range deals with the string subscript out_of_range error • The class length_error handles the error if − A length greater than the maximum allowed for a string object is used
  • 33. Using C++ Exception Classes (continued) • If the operator new cannot allocate memory space − It throws a bad_alloc exception • The class runtime_error deals with errors that occur only during program execution • Classes overflow_error and underflow_error − Deal with arithmetic overflow and under-flow exceptions − Derived from the class runtime_error
  • 34. Example 15-8: exceptions out_of_range and length_error
  • 35.
  • 36.
  • 38.
  • 39. Creating Your Own Exception Classes • Programmers can create exception classes to handle exceptions not covered by C++’s exception classes and their own exceptions • C++ uses the same mechanism to process the exceptions you define as for built-in exceptions • You must throw your own exceptions using the throw statement • Any class can be an exception class
  • 41.
  • 42.
  • 43.
  • 45.
  • 47.
  • 48.
  • 49. Rethrowing and Throwing an Exception • When an exception occurs in a try block − Control immediately passes to one of the catch blocks • A catch block either − Handles the exception or partially processes the exception and then rethrows the same exception OR − Rethrows another exception for the calling environment to handle
  • 50. Rethrowing and Throwing an Exception (continued) • The general syntax to rethrow an exception caught by a catch block is: (in this case, the same exception is rethrown) or: where expression is a constant value, variable, or object
  • 51. Rethrowing and Throwing an Exception (continued) • The object being thrown can be − A specific object − An anonymous object • A function specifies the exceptions it throws in its heading using the throw clause
  • 52. • A function specifies the exceptions it throws (to be handled somewhere) in its heading using the throw clause. • For example, the following function specifies that it throws exceptions of type int, string, and divisionByZero, where divisionByZero is the class as defined previously.
  • 54.
  • 55.
  • 56. Exception Handling Techniques • When an exception occurs, the programmer usually has three choices: − Terminate the program − Include code to recover from the exception − Log the error and continue
  • 57. Terminate the Program • In some cases, it is best to let the program terminate when an exception occurs • For example, if the input file does not exist when the program executes − There is no point in continuing with the program • The program can output an appropriate error message and terminate
  • 58. Fix the Error and Continue • In some cases, you will want to handle the exception and let the program continue • For example, if a user inputs a letter in place of a number − The input stream will enter the fail state • You can include the necessary code to keep prompting the user to input a number until the entry is valid
  • 59. Log the Error and Continue • For example, if your program is designed to run a nuclear reactor or continuously monitor a satellite − It cannot be terminated if an exception occurs • When an exception occurs − The program should write the exception into a file and continue to run
  • 61.
  • 62.
  • 63. Stack Unwinding • When an exception is thrown in, say, a function, the function can do the following: − Do nothing − Partially process the exception and throw the same exception or a new exception − Throw a new exception
  • 64. Stack Unwinding (continued) • In each of these cases, the function-call stack is unwound − The exception can be caught in the next try/catch block • When the function-call stack is unwound − The function in which the exception was not caught and/or rethrown terminates − Memory for its local variables is destroyed
  • 65. Stack Unwinding (continued) • The stack unwinding continues until − A try/catch handles the exception or − The program does not handle the exception • If the program does not handle the exception, then the function terminate is called to terminate the program
  • 66.
  • 68.
  • 70.
  • 71. Summary • Exception: an undesirable event detectable during program execution • assert checks whether an expression meets a specified condition and terminates if not met • try/catch block handles exceptions • Statements that may generate an exception are placed in a try block • Catch block specifies the type of exception it can catch and contains an exception handler
  • 72. Summary (continued) • If no exceptions are thrown in a try block, all catch blocks for that try block are ignored and execution resumes after the last catch block • Data type of catch block parameter specifies type of exception that catch block can catch • Catch block can have at most one parameter • exception is base class for exception classes • what returns string containing the exception object thrown by built-in exception classes
  • 73. Summary (continued) • Class exception is in the header file exception • runtime_error handles runtime errors • C++ enables programmers to create their own exception classes • A function specifies the exceptions it throws in its heading using the throw clause • If the program does not handle the exception, then the function terminate terminates the program