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 language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguageTanmay Modi
 
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 language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguage
 
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

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 

Recently uploaded (20)

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 

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. ¨ ¨