SlideShare a Scribd company logo
1 of 4
Download to read offline
For more Https:www.ThesisScientist.com
UNIT 10
EXCEPTION HANDLING
An exception is a run-time error. Proper handling of exceptions is an
important programming issue. This is because exceptions can and do happen in
practice and programs are generally expected to behave gracefully in face of
such exceptions. Unless an exception is properly handled, it is likely to result
in abnormal program termination and potential loss of work. For example, an
undetected division by zero or dereferencing of an invalid pointer will almost
certainly terminate the program abruptly.
Exception handling consists of three things: (i) the detecting of a run-time
error, (ii) raising an exception in response to the error, and (ii) taking
corrective action. The latter is called recovery. Some exceptions can be fully
recovered from so that execution can proceed unaffected. For example, an
invalid argument value passed to a function may be handled by substituting a
reasonable default value for it. Other exceptions can only be partially handled.
For example, exhaustion of the heap memory can be handled by abandoning
the current operation and returning to a state where other operations (such as
saving the currently open files to avoid losing their contents) can be attempted.
C++ provides a language facility for the uniform handling of exceptions.
Under this scheme, a section of code whose execution may lead to run-time
errors is labeled as a try block. Any fragment of code activated during the
execution of a try block can raise an exception using a throw clause. All
exceptions are typed (i.e., each exception is denoted by an object of a specific
type). A try block is followed by one or more catch clauses. Each catch
clause is responsible for the handling of exceptions of a particular type.
When an exception is raised, its type is compared against the catch clauses
following it. If a matching clause is found then its handler is executed.
Otherwise, the exception is propagated up, to an immediately enclosing try
block (if any). The process is repeated until either the exception is handled by
a matching catch clause or it is handled by a default handler.
FLOW CONTROL
Figure 10.1 illustrates the flow of control during exception handling. It shows
a function e with a try block from which it calls f; f calls another function g
from its own try block, which in turn calls h. Each of the try blocks is followed
by a list of catch clauses. Function h throws an exception of type B. The
enclosing try block's catch clauses are examined (i.e., A and E); neither
matches B. The exception is therefore propagated to the catch clauses of the
enclosing try block (i.e., C and D), which do not match B either. Propagating
the exception further up, the catch clauses following the try block in e (i.e., A,
B, and C) are examined next, resulting in a match.
At this point flow of control is transferred from where the exception was
raised in h to the catch clause in e. The intervening stack frames for h, g, and f
are unwound: all automatic objects created by these functions are properly
destroyed by implicit calls to their destructors.
Figure 10.1 Flow control in exception handling.
tryblock
catch clauses
A
B
C
tryblock
catch clauses
C
D
tryblock
catch clauses
A
E
function e
function f
function g
function h
f(...);
g(...);
h(...);
throwB
The Throw Clauses
An exception is raised by a throw clause, which has the general form
throw object;
where object is an object of a built-in or user-defined type. Since an exception
is matched by the type of object and not its value, it is customary to define
classes for this exact purpose.
 An attempt to push onto a full stack results in an overflow. We raise an
Overflow exception in response to this:
For more Https:www.ThesisScientist.com
template <class Type>
void Stack<Type>::Push (Type &val)
{
if (top+1 < maxSize)
stack[++top] = val;
else
throw Overflow();
}
 An attempt to pop from an empty stack results in an underflow. We raise
an Underflow exception in response to this:
template <class Type>
void Stack<Type>::Pop (void)
{
if (top >= 0)
--top;
else
throw Underflow();
}
 Attempting to examine the top element of an empty stack is clearly an
error. We raise an Empty exception in response to this:
template <class Type>
Type &Stack<Type>::Top (void)
{
if (top < 0)
throw Empty();
return stack[top];
}
The Try Block And catch Block ¨
A code fragment whose execution may potentially raise exceptions is enclosed
by a try block, which has the general form
try {
statements
}
where statements represents one or more semicolon-terminated statements. In
other words, a try block is like a compound statement preceded by the try
keyword.
A try block is followed by catch clauses for the exceptions which may be
raised during the execution of the block. The role of the catch clauses is to
handle the respective exceptions. A catch clause (also called a handler) has
the general form
catch (type par) { statements }
where type is the type of the object raised by the matching exception, par is
optional and is an identifier bound to the object raised by the exception, and
statements represents zero or more semicolon-terminated statements.
For example, continuing with our Stack class, we may write:
try {
Stack<int> s(3);
s.Push(10);
//...
s.Pop();
//...
}
catch (Underflow) {cout << "Stack underflown";}
catch (Overflow) {cout << "Stack overflown";}
catch (HeapFail) {cout << "Heap exhaustedn";}
catch (BadSize) {cout << "Bad stack sizen";}
catch (Empty) {cout << "Empty stackn";}
For simplicity, the catch clauses here do nothing more than outputting a
relevant message.
When an exception is raised by the code within the try block, the catch
clauses are examined in the order they appear. The first matching catch clause
is selected and its statements are executed. The remaining catch clauses are
ignored.
A catch clause (of type C) matches an exception (of type E) if:
 C and E are the same type, or
 One is a reference or constant of the other type, or
 One is a nonprivate base class of the other type, or
 Both are pointers and one can be converted to another by implicit type
conversion rules.
¨
¨

More Related Content

What's hot

Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2ppd1961
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Janki Shah
 
Exception handler
Exception handler Exception handler
Exception handler dishni
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++imran khan
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
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
Exception handlingException handling
Exception handlingIblesoft
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .NetMindfire Solutions
 

What's hot (20)

Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Exception handler
Exception handler Exception handler
Exception handler
 
C++ ala
C++ alaC++ ala
C++ ala
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Exception handling
Exception handlingException handling
Exception handling
 
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
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
 
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
 
F6dc1 session6 c++
F6dc1 session6 c++F6dc1 session6 c++
F6dc1 session6 c++
 
Exception handling
Exception handlingException handling
Exception handling
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
 

Similar to EXCEPTION HANDLING in C++

Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguageTanmay Modi
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c languagechintupro9
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)Jyoti Bhardwaj
 
Btech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statementsBtech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statementsRai University
 
C++ decision making
C++ decision makingC++ decision making
C++ decision makingZohaib Ahmed
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 

Similar to EXCEPTION HANDLING in C++ (20)

7 decision-control
7 decision-control7 decision-control
7 decision-control
 
Exception handling
Exception handlingException handling
Exception handling
 
Java unit3
Java unit3Java unit3
Java unit3
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguage
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
Loops and iteration.docx
Loops and iteration.docxLoops and iteration.docx
Loops and iteration.docx
 
Controls & Loops in C
Controls & Loops in C Controls & Loops in C
Controls & Loops in C
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
CONTROL STMTS.pptx
CONTROL STMTS.pptxCONTROL STMTS.pptx
CONTROL STMTS.pptx
 
Control structures
Control structuresControl structures
Control structures
 
Btech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statementsBtech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statements
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Notes on c++
Notes on c++Notes on c++
Notes on c++
 

More from Prof Ansari

Sci Hub New Domain
Sci Hub New DomainSci Hub New Domain
Sci Hub New DomainProf Ansari
 
Sci Hub cc Not Working
Sci Hub cc Not WorkingSci Hub cc Not Working
Sci Hub cc Not WorkingProf Ansari
 
basics of computer network
basics of computer networkbasics of computer network
basics of computer networkProf Ansari
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTIONProf Ansari
 
Project Evaluation and Estimation in Software Development
Project Evaluation and Estimation in Software DevelopmentProject Evaluation and Estimation in Software Development
Project Evaluation and Estimation in Software DevelopmentProf Ansari
 
Stepwise Project planning in software development
Stepwise Project planning in software developmentStepwise Project planning in software development
Stepwise Project planning in software developmentProf Ansari
 
Database and Math Relations
Database and Math RelationsDatabase and Math Relations
Database and Math RelationsProf Ansari
 
Normalisation in Database management System (DBMS)
Normalisation in Database management System (DBMS)Normalisation in Database management System (DBMS)
Normalisation in Database management System (DBMS)Prof Ansari
 
Entity-Relationship Data Model in DBMS
Entity-Relationship Data Model in DBMSEntity-Relationship Data Model in DBMS
Entity-Relationship Data Model in DBMSProf Ansari
 
A Detail Database Architecture
A Detail Database ArchitectureA Detail Database Architecture
A Detail Database ArchitectureProf Ansari
 
INTRODUCTION TO Database Management System (DBMS)
INTRODUCTION TO Database Management System (DBMS)INTRODUCTION TO Database Management System (DBMS)
INTRODUCTION TO Database Management System (DBMS)Prof Ansari
 
Master thesis on Vehicular Ad hoc Networks (VANET)
Master thesis on Vehicular Ad hoc Networks (VANET)Master thesis on Vehicular Ad hoc Networks (VANET)
Master thesis on Vehicular Ad hoc Networks (VANET)Prof Ansari
 
Master Thesis on Vehicular Ad-hoc Network (VANET)
Master Thesis on Vehicular Ad-hoc Network (VANET)Master Thesis on Vehicular Ad-hoc Network (VANET)
Master Thesis on Vehicular Ad-hoc Network (VANET)Prof Ansari
 
INTERFACING WITH INTEL 8251A (USART)
INTERFACING WITH INTEL 8251A (USART)INTERFACING WITH INTEL 8251A (USART)
INTERFACING WITH INTEL 8251A (USART)Prof Ansari
 
HOST AND NETWORK SECURITY by ThesisScientist.com
HOST AND NETWORK SECURITY by ThesisScientist.comHOST AND NETWORK SECURITY by ThesisScientist.com
HOST AND NETWORK SECURITY by ThesisScientist.comProf Ansari
 
SYSTEM NETWORK ADMINISTRATIONS GOALS and TIPS
SYSTEM NETWORK ADMINISTRATIONS GOALS and TIPSSYSTEM NETWORK ADMINISTRATIONS GOALS and TIPS
SYSTEM NETWORK ADMINISTRATIONS GOALS and TIPSProf Ansari
 
INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS Prof Ansari
 
introduction to Blogging ppt
introduction to Blogging pptintroduction to Blogging ppt
introduction to Blogging pptProf Ansari
 
INTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERINGINTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERINGProf Ansari
 
Introduction to E-commerce
Introduction to E-commerceIntroduction to E-commerce
Introduction to E-commerceProf Ansari
 

More from Prof Ansari (20)

Sci Hub New Domain
Sci Hub New DomainSci Hub New Domain
Sci Hub New Domain
 
Sci Hub cc Not Working
Sci Hub cc Not WorkingSci Hub cc Not Working
Sci Hub cc Not Working
 
basics of computer network
basics of computer networkbasics of computer network
basics of computer network
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
 
Project Evaluation and Estimation in Software Development
Project Evaluation and Estimation in Software DevelopmentProject Evaluation and Estimation in Software Development
Project Evaluation and Estimation in Software Development
 
Stepwise Project planning in software development
Stepwise Project planning in software developmentStepwise Project planning in software development
Stepwise Project planning in software development
 
Database and Math Relations
Database and Math RelationsDatabase and Math Relations
Database and Math Relations
 
Normalisation in Database management System (DBMS)
Normalisation in Database management System (DBMS)Normalisation in Database management System (DBMS)
Normalisation in Database management System (DBMS)
 
Entity-Relationship Data Model in DBMS
Entity-Relationship Data Model in DBMSEntity-Relationship Data Model in DBMS
Entity-Relationship Data Model in DBMS
 
A Detail Database Architecture
A Detail Database ArchitectureA Detail Database Architecture
A Detail Database Architecture
 
INTRODUCTION TO Database Management System (DBMS)
INTRODUCTION TO Database Management System (DBMS)INTRODUCTION TO Database Management System (DBMS)
INTRODUCTION TO Database Management System (DBMS)
 
Master thesis on Vehicular Ad hoc Networks (VANET)
Master thesis on Vehicular Ad hoc Networks (VANET)Master thesis on Vehicular Ad hoc Networks (VANET)
Master thesis on Vehicular Ad hoc Networks (VANET)
 
Master Thesis on Vehicular Ad-hoc Network (VANET)
Master Thesis on Vehicular Ad-hoc Network (VANET)Master Thesis on Vehicular Ad-hoc Network (VANET)
Master Thesis on Vehicular Ad-hoc Network (VANET)
 
INTERFACING WITH INTEL 8251A (USART)
INTERFACING WITH INTEL 8251A (USART)INTERFACING WITH INTEL 8251A (USART)
INTERFACING WITH INTEL 8251A (USART)
 
HOST AND NETWORK SECURITY by ThesisScientist.com
HOST AND NETWORK SECURITY by ThesisScientist.comHOST AND NETWORK SECURITY by ThesisScientist.com
HOST AND NETWORK SECURITY by ThesisScientist.com
 
SYSTEM NETWORK ADMINISTRATIONS GOALS and TIPS
SYSTEM NETWORK ADMINISTRATIONS GOALS and TIPSSYSTEM NETWORK ADMINISTRATIONS GOALS and TIPS
SYSTEM NETWORK ADMINISTRATIONS GOALS and TIPS
 
INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS
 
introduction to Blogging ppt
introduction to Blogging pptintroduction to Blogging ppt
introduction to Blogging ppt
 
INTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERINGINTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERING
 
Introduction to E-commerce
Introduction to E-commerceIntroduction to E-commerce
Introduction to E-commerce
 

Recently uploaded

Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersMairaAshraf6
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...Health
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfsmsksolar
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 

Recently uploaded (20)

Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 

EXCEPTION HANDLING in C++

  • 1. For more Https:www.ThesisScientist.com UNIT 10 EXCEPTION HANDLING An exception is a run-time error. Proper handling of exceptions is an important programming issue. This is because exceptions can and do happen in practice and programs are generally expected to behave gracefully in face of such exceptions. Unless an exception is properly handled, it is likely to result in abnormal program termination and potential loss of work. For example, an undetected division by zero or dereferencing of an invalid pointer will almost certainly terminate the program abruptly. Exception handling consists of three things: (i) the detecting of a run-time error, (ii) raising an exception in response to the error, and (ii) taking corrective action. The latter is called recovery. Some exceptions can be fully recovered from so that execution can proceed unaffected. For example, an invalid argument value passed to a function may be handled by substituting a reasonable default value for it. Other exceptions can only be partially handled. For example, exhaustion of the heap memory can be handled by abandoning the current operation and returning to a state where other operations (such as saving the currently open files to avoid losing their contents) can be attempted. C++ provides a language facility for the uniform handling of exceptions. Under this scheme, a section of code whose execution may lead to run-time errors is labeled as a try block. Any fragment of code activated during the execution of a try block can raise an exception using a throw clause. All exceptions are typed (i.e., each exception is denoted by an object of a specific type). A try block is followed by one or more catch clauses. Each catch clause is responsible for the handling of exceptions of a particular type. When an exception is raised, its type is compared against the catch clauses following it. If a matching clause is found then its handler is executed. Otherwise, the exception is propagated up, to an immediately enclosing try block (if any). The process is repeated until either the exception is handled by a matching catch clause or it is handled by a default handler. FLOW CONTROL Figure 10.1 illustrates the flow of control during exception handling. It shows a function e with a try block from which it calls f; f calls another function g from its own try block, which in turn calls h. Each of the try blocks is followed by a list of catch clauses. Function h throws an exception of type B. The
  • 2. enclosing try block's catch clauses are examined (i.e., A and E); neither matches B. The exception is therefore propagated to the catch clauses of the enclosing try block (i.e., C and D), which do not match B either. Propagating the exception further up, the catch clauses following the try block in e (i.e., A, B, and C) are examined next, resulting in a match. At this point flow of control is transferred from where the exception was raised in h to the catch clause in e. The intervening stack frames for h, g, and f are unwound: all automatic objects created by these functions are properly destroyed by implicit calls to their destructors. Figure 10.1 Flow control in exception handling. tryblock catch clauses A B C tryblock catch clauses C D tryblock catch clauses A E function e function f function g function h f(...); g(...); h(...); throwB The Throw Clauses An exception is raised by a throw clause, which has the general form throw object; where object is an object of a built-in or user-defined type. Since an exception is matched by the type of object and not its value, it is customary to define classes for this exact purpose.  An attempt to push onto a full stack results in an overflow. We raise an Overflow exception in response to this:
  • 3. For more Https:www.ThesisScientist.com template <class Type> void Stack<Type>::Push (Type &val) { if (top+1 < maxSize) stack[++top] = val; else throw Overflow(); }  An attempt to pop from an empty stack results in an underflow. We raise an Underflow exception in response to this: template <class Type> void Stack<Type>::Pop (void) { if (top >= 0) --top; else throw Underflow(); }  Attempting to examine the top element of an empty stack is clearly an error. We raise an Empty exception in response to this: template <class Type> Type &Stack<Type>::Top (void) { if (top < 0) throw Empty(); return stack[top]; } The Try Block And catch Block ¨ A code fragment whose execution may potentially raise exceptions is enclosed by a try block, which has the general form try { statements } where statements represents one or more semicolon-terminated statements. In other words, a try block is like a compound statement preceded by the try keyword. A try block is followed by catch clauses for the exceptions which may be raised during the execution of the block. The role of the catch clauses is to
  • 4. handle the respective exceptions. A catch clause (also called a handler) has the general form catch (type par) { statements } where type is the type of the object raised by the matching exception, par is optional and is an identifier bound to the object raised by the exception, and statements represents zero or more semicolon-terminated statements. For example, continuing with our Stack class, we may write: try { Stack<int> s(3); s.Push(10); //... s.Pop(); //... } catch (Underflow) {cout << "Stack underflown";} catch (Overflow) {cout << "Stack overflown";} catch (HeapFail) {cout << "Heap exhaustedn";} catch (BadSize) {cout << "Bad stack sizen";} catch (Empty) {cout << "Empty stackn";} For simplicity, the catch clauses here do nothing more than outputting a relevant message. When an exception is raised by the code within the try block, the catch clauses are examined in the order they appear. The first matching catch clause is selected and its statements are executed. The remaining catch clauses are ignored. A catch clause (of type C) matches an exception (of type E) if:  C and E are the same type, or  One is a reference or constant of the other type, or  One is a nonprivate base class of the other type, or  Both are pointers and one can be converted to another by implicit type conversion rules. ¨ ¨