Exception Handling
PCCP, FPGDST 2003 2
© CDAC (Formerly NCST)
Objectives
 Concept of exceptions
–why a better error handling
mechanism is required
 C++ support for exceptions and
exception handling
PCCP, FPGDST 2003 3
© CDAC (Formerly NCST)
Introduction
 Error free program operation is a dream
 Why error handling mechanism is
required
–To check the abnormality of program.
–To avoid the cascading effect of error.
–To avoid abnormal termination
 Proper corrective action has to be taken
 Errors have to be handled
PCCP, FPGDST 2003 4
© CDAC (Formerly NCST)
C Mechanism
 Set a global error flag
 Expect the user to check after each operation
 Lot of responsibility placed on the user
 Example -
int fd;
fd = open(“hello.dat”, O_RDONLY);
if ( fd == -1 )
// do something
File *fp;
fp = fopen(“hello.dat”, “r”);
if ( fp == NULL )
if ( errno == FILENOTFOUND )
// do something
conventional error
handling
PCCP, FPGDST 2003 5
© CDAC (Formerly NCST)
Java Mechanism
 Uses the special key word
– throw, try, catch, throws and finally
 Program inside a try block can throw error and can be caught ouside of that
block or in parent block.
void readReport(String filename){
try {
File file = new File(filename);
SimpleInput sin = new SimpleInput(file);
// read data from file
}
catch (FileNotFoundException fnfe) {
System.err.println(“Missing report file: ”+filename);
}
}
PCCP, FPGDST 2003 6
© CDAC (Formerly NCST)
C++ Mechanism
 To handle the error uses the exception
 Program that finds a problem it cannot
cope with, throws an exception, hoping
that its caller can handle the problem
 Uses the key word
–try, catch, throw
PCCP, FPGDST 2003 7
© CDAC (Formerly NCST)
Exception Handler
 Code block has to be willing to catch an
exception
 Block is called exception handler
 Specified using catch
 Must follow a try block or another
exception handler
PCCP, FPGDST 2003 8
© CDAC (Formerly NCST)
exception that occurred
Illustration
try {
. . .
. . . // error occurred here
}
catch (...)
{
. . .
. . . // error handling code
}
try block
catch block
PCCP, FPGDST 2003 9
© CDAC (Formerly NCST)
Exception Handler (contd…)
 try Block
– Contains code that can throw an exception
 catch Block
– Entered when an exception is thrown
– Parentheses of catch block contains an expression
Similar to method argument
– Specifies type of objects with which the handler
can be entered
catch (…) is default exception handler.
– Naming the argument is optional
PCCP, FPGDST 2003 10
© CDAC (Formerly NCST)
Throwing an Exception
 Exception thrown using throw
statement
 Any exceptions thrown in the exception
handler must be dealt with by the caller
of the try block
 Exception caught by specifying type
 Object is thrown, not type
PCCP, FPGDST 2003 11
© CDAC (Formerly NCST)
Example
try
{
Object myObj(”my value”);
throw myObj;
}
catch ( Object err )
{
// statements in which the thrown
Object exceptions are processed
cerr << err.m_msg << endl;
}
Object type
object
m_msg is a
public member
of Object
PCCP, FPGDST 2003 12
© CDAC (Formerly NCST)
Searching
 Throwing and catching involves search for a
matching handler
 Search
– in the exception call chain
– from the throw point
 During search
– call stack is unwound
– destructors for local objects are invoked
 Handler not found
– The program will terminate abnormally
PCCP, FPGDST 2003 13
© CDAC (Formerly NCST)
Example
#include <iostream.h>
#include <string>
class Object {
string name;
public:
Object(string name) : name(name) {
cout << "Object constructor of " <<name << "n";
}
Object(Object const &other) : name(other.name + "
(copy)") {
cout << "Copy constructor for " << name << "n";
}
~Object(){
cout << "Object destructor of " << name << "n";
}
void hello() {
cout << "Hello by " << name << "n";
}
PCCP, FPGDST 2003 14
© CDAC (Formerly NCST)
Example
void fun() {
Object toThrow("'local object'");
cout << "Object fun() of " << name << "n";
throw toThrow;
}
}; //class Object ends:
int main(){
Object out("'main object'");
try {
out.fun();
}
catch (Object o) {
cout << "Caught exceptionn";
o.hello();
}
}
PCCP, FPGDST 2003 15
© CDAC (Formerly NCST)
Output of Example
Object constructor of 'main object'
Object constructor of 'local object'
Object fun() of 'main object'
Copy constructor for 'local object' (copy)
Object destructor of 'local object'
Copy constructor for 'local object' (copy) (copy)
Caught exception
Hello by 'local object' (copy) (copy)
Object destructor of 'local object' (copy) (copy)
Object destructor of 'local object' (copy)
Object destructor of 'main object'
PCCP, FPGDST 2003 16
© CDAC (Formerly NCST)
Handling Multiple Exceptions
 Discrimination between two exceptions
possible
 Add multiple catch blocks for a try
block
 Appropriate handler will be invoked
when the exception occurs
PCCP, FPGDST 2003 17
© CDAC (Formerly NCST)
Handling Multiple Exceptions (contd…)
try {
// this code may throw different types of exceptions
}
catch (char *message) {
// code to process char pointers
}
catch (int value) {
// code to process ints
}
catch (...) {
// code to process other exceptions,
// often passing the exception on to outer
// level exception handlers:
throw;
}
PCCP, FPGDST 2003 18
© CDAC (Formerly NCST)
Example
void f1() {
try {
Object toThrow("‘new object'");
throw toThrow;
} catch ( Object o ) {
o.hello();
throw “Caught Object exception”;
}
}
throw an
exception explicitly
catch exception, but
throw a different one
PCCP, FPGDST 2003 19
© CDAC (Formerly NCST)
Example
void f2() {
try {
f1();
} catch ( char *errmsg ) {
// safely caught
}
}
exception caught
PCCP, FPGDST 2003 20
© CDAC (Formerly NCST)
Nesting
 Exceptions can be nested
try {
// some code
try {
// some code
} catch ( InnerException ) {
// handle InnerException
}
} catch ( OuterException ) {
// handle OuterException
}
PCCP, FPGDST 2003 21
© CDAC (Formerly NCST)
Exception Hierarchies
 Exceptions can be grouped
 Two ways
–define variations as enumeration
–derive using inheritance
 Organizing exceptions is important for
robustness of code
PCCP, FPGDST 2003 22
© CDAC (Formerly NCST)
Grouping
 Exceptions can be grouped using enum
 Thrown exception object identified using
enum identifier
PCCP, FPGDST 2003 23
© CDAC (Formerly NCST)
Example
enum NetworkError { HostNotFound,
BadPort };
try {
. . .
} catch ( NetworkError ne ) {
switch ( ne ) {
case HostNotFound : . . .; break;
case BadPort : . . .; break;
}
}
PCCP, FPGDST 2003 24
© CDAC (Formerly NCST)
Hierarchies
 Exception hierarchies using inheritance
possible
 Use inheritance instead of enum
 More flexible and extensible
 Advantages of classes and the property
of inheritance can be used
PCCP, FPGDST 2003 25
© CDAC (Formerly NCST)
Example
class NetworkError { };
class HostNotFound : public NetworkError { };
class BadPort : public NetworkError { };
try {
Socket s;
s.connect(“konark”, 80);
String buf = s.readInput();
}
catch ( HostNotFound ) {
}
catch ( BadPort ) {
}
catch ( NetworkError ) {
}
PCCP, FPGDST 2003 26
© CDAC (Formerly NCST)
Exception Resolution
 Exceptions can be caught by a handler
using the base class rather than the
exact class
 Semantics for handler catching and
naming are identical to that of a function
 Pointers and references can be used to
avoid losing information
PCCP, FPGDST 2003 27
© CDAC (Formerly NCST)
Exception Matching
 Order of handlers is important
 Handlers are tried in order
PCCP, FPGDST 2003 28
© CDAC (Formerly NCST)
Example
class NetworkError { };
class HostNotFound : public NetworkError { };
class BadPort : public NetworkError { };
try {
Socket s; s.connect(“konark”, 80);
String buf = s.readInput();
}
catch ( NetworkError ) {
}
catch ( HostNotFound ) {
}
catch ( BadPort ) {
}
never
caught
PCCP, FPGDST 2003 29
© CDAC (Formerly NCST)
Re-throwing an Exception
 Handler can re-throw an exception
 throw used without an argument
 Exception re-thrown is original
exception thrown
PCCP, FPGDST 2003 30
© CDAC (Formerly NCST)
Example
void f1() {
try {
Object toThrow("‘new object'");
throw toThrow;
} catch ( Object o ) {
throw; // re-throw exception
}
}
try {
f1();
}
catch ( Object err ) { . . .}
original exception
caught
PCCP, FPGDST 2003 31
© CDAC (Formerly NCST)
Exception specifications
 Set of exceptions that a function may throw,
can be specified as a part of the function
declaration.
void f(int a) throw(Exception1, ..) {…
 It guarantees that function will not throw any
other types of exception.
 If during execution function does something
that tries to abrogate the guarantee. The
attempt will be transferred to
std::unexpected()
 Std::unexpected => std::terminate()
PCCP, FPGDST 2003 32
© CDAC (Formerly NCST)
Exception Specification & ptr to ()
 An exception specification can also be provided in the
declaration of a pointer to function.
 Assignment for pointers to function with exception
specification:
Example:
void func1(int) throw();
void func2(int)throw(string,exceptionType1);
pf = func1; /* okay: func1() is more
restrictive */
pf = func2; /* error: func2() is less
restrictive */
void (*pf)(int) throw (string);
PCCP, FPGDST 2003 33
© CDAC (Formerly NCST)
Standard exceptions
Standard exception thrown by language:
Name Thrown by
Bad_alloc
Bad_cast
Bad_typeid
Bad_exception
new
dynamic_cast
typeid
Exception-
specificficat
ion
PCCP, FPGDST 2003 34
© CDAC (Formerly NCST)
Standard Exceptions
 Thrown by the Standard Library
Name Thrown by
out_of_range
invalid_argument
overflow_error
ios_base::failure
at()
bitset<>::operator[]()
bitset constructor
bitset<>::to_ulong()
ios_base::clear
PCCP, FPGDST 2003 35
© CDAC (Formerly NCST)
Standard exception class
class exception
{
Public:
exception() throw();
exception(const exception&) throw();
exception& operator =(const exception&)
throw();
virtual ~exception();
virtual const char* what() const throw();
Private:
//
};
PCCP, FPGDST 2003 36
© CDAC (Formerly NCST)
Exception Class Hierarchy
exception
run time error
logic_error
bad_alloc
bad_exception
ios_base::failure
bad_typeid
bad_cast
range_error
underflow_
error
overflow_error
Invalid_arguments
out_of_range
domain_
error
lenth_error
PCCP, FPGDST 2003 37
© CDAC (Formerly NCST)
Benefits
 Provides an alternative to traditional
techniques of error checking
 Explicit separation of error handling and
regular code possible
 More regular style of error handling
 Simplifies reuse
PCCP, FPGDST 2003 38
© CDAC (Formerly NCST)
Summary
 Exception handling mechanism is better
 try, catch for exception handling
 Multiple exceptions can be handled
 Exception hierarchy can be created

More Related Content

PPT
Exception handling
PPT
Handling Exceptions In C &amp; C++ [Part B] Ver 2
PPTX
CAP444Unit6ExceptionHandling.pptx
PDF
The Big Three
PPTX
6-Exception Handling and Templates.pptx
PPT
Microkernel Development
PPTX
Object Oriented Programming Using C++: C++ Exception Handling.pptx
PDF
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
Exception handling
Handling Exceptions In C &amp; C++ [Part B] Ver 2
CAP444Unit6ExceptionHandling.pptx
The Big Three
6-Exception Handling and Templates.pptx
Microkernel Development
Object Oriented Programming Using C++: C++ Exception Handling.pptx
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)

Similar to exceptiondddddddddddddddddddddddddddddddddddddddd.ppt (20)

PDF
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
ODP
Jersey Guice AOP
PPTX
Design pattern - part 3
PPTX
Binary patching for fun and profit @ JUG.ru, 25.02.2012
PPTX
exception handling in cpp
PPTX
Unit II Java & J2EE regarding Java application development
PDF
C++ aptitude
DOCX
PDF
Riga Dev Day 2016 - Having fun with Javassist
PDF
PROGRAM 2 – Fraction Class Problem For this programming as.pdf
PDF
Oop10 6
PPTX
Exception handling
PDF
JavaOne 2015 - Having fun with Javassist
PPT
Lecture16
PPT
Exception handling and templates
PDF
Silicon Valley JUG: JVM Mechanics
PPT
data Structure Lecture 1
PPTX
Network simulator 2
PDF
Refactoring for testability c++
PPT
Exception Handling1
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
Jersey Guice AOP
Design pattern - part 3
Binary patching for fun and profit @ JUG.ru, 25.02.2012
exception handling in cpp
Unit II Java & J2EE regarding Java application development
C++ aptitude
Riga Dev Day 2016 - Having fun with Javassist
PROGRAM 2 – Fraction Class Problem For this programming as.pdf
Oop10 6
Exception handling
JavaOne 2015 - Having fun with Javassist
Lecture16
Exception handling and templates
Silicon Valley JUG: JVM Mechanics
data Structure Lecture 1
Network simulator 2
Refactoring for testability c++
Exception Handling1
Ad

Recently uploaded (20)

PDF
LSR CASEBOOK 2024-25.pdf. very nice casbook
PPT
pwm ppt .pdf long description of pwm....
PPTX
CYBER SECURITY PPT.pptx CYBER SECURITY APPLICATION AND USAGE
PDF
Environmental-social-and-governance-report.pdf
PPTX
Unit 1- Introduction to Corporate Etiquettes
PPTX
_Dispute Resolution_July 2022.pptxmhhghhhh
PPTX
Digital Education Presentation for students.
PPTX
employee on boarding for jobs for freshers try it
PPT
Woman as Engineer and Technicians in the field of Clinical & Biomedical Engin...
PPTX
Final Second DC Messeting PPT-Pradeep.M final.pptx
PPTX
formulation and evaluation of polyherbal antiageing cream
PDF
Women’s Talk Session 1- Talking about women
PPTX
mathsportfoliomanvi-211121071838 (1).pptx
PPTX
STS CHAP 4 human development as reflected
PPT
NO000387 (1).pptsbsnsnsnsnsnsnsmsnnsnsnsjsnnsnsnsnnsnnansnwjwnshshshs
PPTX
Unit 3 Presentation Etiquette Business and Corporate Etiquette
PPTX
Creating-a-Personal-Blockchain-Portfolio-for-Developers-and-Experts.pptx
PPTX
430838499-Anaesthesiiiia-Equipmenooot.pptx
PPTX
Session 4 of vibale oldin sink about vola
PPTX
Core Characteristics and Abilities of an Effective Teacher_0.pptx
LSR CASEBOOK 2024-25.pdf. very nice casbook
pwm ppt .pdf long description of pwm....
CYBER SECURITY PPT.pptx CYBER SECURITY APPLICATION AND USAGE
Environmental-social-and-governance-report.pdf
Unit 1- Introduction to Corporate Etiquettes
_Dispute Resolution_July 2022.pptxmhhghhhh
Digital Education Presentation for students.
employee on boarding for jobs for freshers try it
Woman as Engineer and Technicians in the field of Clinical & Biomedical Engin...
Final Second DC Messeting PPT-Pradeep.M final.pptx
formulation and evaluation of polyherbal antiageing cream
Women’s Talk Session 1- Talking about women
mathsportfoliomanvi-211121071838 (1).pptx
STS CHAP 4 human development as reflected
NO000387 (1).pptsbsnsnsnsnsnsnsmsnnsnsnsjsnnsnsnsnnsnnansnwjwnshshshs
Unit 3 Presentation Etiquette Business and Corporate Etiquette
Creating-a-Personal-Blockchain-Portfolio-for-Developers-and-Experts.pptx
430838499-Anaesthesiiiia-Equipmenooot.pptx
Session 4 of vibale oldin sink about vola
Core Characteristics and Abilities of an Effective Teacher_0.pptx
Ad

exceptiondddddddddddddddddddddddddddddddddddddddd.ppt

  • 2. PCCP, FPGDST 2003 2 © CDAC (Formerly NCST) Objectives  Concept of exceptions –why a better error handling mechanism is required  C++ support for exceptions and exception handling
  • 3. PCCP, FPGDST 2003 3 © CDAC (Formerly NCST) Introduction  Error free program operation is a dream  Why error handling mechanism is required –To check the abnormality of program. –To avoid the cascading effect of error. –To avoid abnormal termination  Proper corrective action has to be taken  Errors have to be handled
  • 4. PCCP, FPGDST 2003 4 © CDAC (Formerly NCST) C Mechanism  Set a global error flag  Expect the user to check after each operation  Lot of responsibility placed on the user  Example - int fd; fd = open(“hello.dat”, O_RDONLY); if ( fd == -1 ) // do something File *fp; fp = fopen(“hello.dat”, “r”); if ( fp == NULL ) if ( errno == FILENOTFOUND ) // do something conventional error handling
  • 5. PCCP, FPGDST 2003 5 © CDAC (Formerly NCST) Java Mechanism  Uses the special key word – throw, try, catch, throws and finally  Program inside a try block can throw error and can be caught ouside of that block or in parent block. void readReport(String filename){ try { File file = new File(filename); SimpleInput sin = new SimpleInput(file); // read data from file } catch (FileNotFoundException fnfe) { System.err.println(“Missing report file: ”+filename); } }
  • 6. PCCP, FPGDST 2003 6 © CDAC (Formerly NCST) C++ Mechanism  To handle the error uses the exception  Program that finds a problem it cannot cope with, throws an exception, hoping that its caller can handle the problem  Uses the key word –try, catch, throw
  • 7. PCCP, FPGDST 2003 7 © CDAC (Formerly NCST) Exception Handler  Code block has to be willing to catch an exception  Block is called exception handler  Specified using catch  Must follow a try block or another exception handler
  • 8. PCCP, FPGDST 2003 8 © CDAC (Formerly NCST) exception that occurred Illustration try { . . . . . . // error occurred here } catch (...) { . . . . . . // error handling code } try block catch block
  • 9. PCCP, FPGDST 2003 9 © CDAC (Formerly NCST) Exception Handler (contd…)  try Block – Contains code that can throw an exception  catch Block – Entered when an exception is thrown – Parentheses of catch block contains an expression Similar to method argument – Specifies type of objects with which the handler can be entered catch (…) is default exception handler. – Naming the argument is optional
  • 10. PCCP, FPGDST 2003 10 © CDAC (Formerly NCST) Throwing an Exception  Exception thrown using throw statement  Any exceptions thrown in the exception handler must be dealt with by the caller of the try block  Exception caught by specifying type  Object is thrown, not type
  • 11. PCCP, FPGDST 2003 11 © CDAC (Formerly NCST) Example try { Object myObj(”my value”); throw myObj; } catch ( Object err ) { // statements in which the thrown Object exceptions are processed cerr << err.m_msg << endl; } Object type object m_msg is a public member of Object
  • 12. PCCP, FPGDST 2003 12 © CDAC (Formerly NCST) Searching  Throwing and catching involves search for a matching handler  Search – in the exception call chain – from the throw point  During search – call stack is unwound – destructors for local objects are invoked  Handler not found – The program will terminate abnormally
  • 13. PCCP, FPGDST 2003 13 © CDAC (Formerly NCST) Example #include <iostream.h> #include <string> class Object { string name; public: Object(string name) : name(name) { cout << "Object constructor of " <<name << "n"; } Object(Object const &other) : name(other.name + " (copy)") { cout << "Copy constructor for " << name << "n"; } ~Object(){ cout << "Object destructor of " << name << "n"; } void hello() { cout << "Hello by " << name << "n"; }
  • 14. PCCP, FPGDST 2003 14 © CDAC (Formerly NCST) Example void fun() { Object toThrow("'local object'"); cout << "Object fun() of " << name << "n"; throw toThrow; } }; //class Object ends: int main(){ Object out("'main object'"); try { out.fun(); } catch (Object o) { cout << "Caught exceptionn"; o.hello(); } }
  • 15. PCCP, FPGDST 2003 15 © CDAC (Formerly NCST) Output of Example Object constructor of 'main object' Object constructor of 'local object' Object fun() of 'main object' Copy constructor for 'local object' (copy) Object destructor of 'local object' Copy constructor for 'local object' (copy) (copy) Caught exception Hello by 'local object' (copy) (copy) Object destructor of 'local object' (copy) (copy) Object destructor of 'local object' (copy) Object destructor of 'main object'
  • 16. PCCP, FPGDST 2003 16 © CDAC (Formerly NCST) Handling Multiple Exceptions  Discrimination between two exceptions possible  Add multiple catch blocks for a try block  Appropriate handler will be invoked when the exception occurs
  • 17. PCCP, FPGDST 2003 17 © CDAC (Formerly NCST) Handling Multiple Exceptions (contd…) try { // this code may throw different types of exceptions } catch (char *message) { // code to process char pointers } catch (int value) { // code to process ints } catch (...) { // code to process other exceptions, // often passing the exception on to outer // level exception handlers: throw; }
  • 18. PCCP, FPGDST 2003 18 © CDAC (Formerly NCST) Example void f1() { try { Object toThrow("‘new object'"); throw toThrow; } catch ( Object o ) { o.hello(); throw “Caught Object exception”; } } throw an exception explicitly catch exception, but throw a different one
  • 19. PCCP, FPGDST 2003 19 © CDAC (Formerly NCST) Example void f2() { try { f1(); } catch ( char *errmsg ) { // safely caught } } exception caught
  • 20. PCCP, FPGDST 2003 20 © CDAC (Formerly NCST) Nesting  Exceptions can be nested try { // some code try { // some code } catch ( InnerException ) { // handle InnerException } } catch ( OuterException ) { // handle OuterException }
  • 21. PCCP, FPGDST 2003 21 © CDAC (Formerly NCST) Exception Hierarchies  Exceptions can be grouped  Two ways –define variations as enumeration –derive using inheritance  Organizing exceptions is important for robustness of code
  • 22. PCCP, FPGDST 2003 22 © CDAC (Formerly NCST) Grouping  Exceptions can be grouped using enum  Thrown exception object identified using enum identifier
  • 23. PCCP, FPGDST 2003 23 © CDAC (Formerly NCST) Example enum NetworkError { HostNotFound, BadPort }; try { . . . } catch ( NetworkError ne ) { switch ( ne ) { case HostNotFound : . . .; break; case BadPort : . . .; break; } }
  • 24. PCCP, FPGDST 2003 24 © CDAC (Formerly NCST) Hierarchies  Exception hierarchies using inheritance possible  Use inheritance instead of enum  More flexible and extensible  Advantages of classes and the property of inheritance can be used
  • 25. PCCP, FPGDST 2003 25 © CDAC (Formerly NCST) Example class NetworkError { }; class HostNotFound : public NetworkError { }; class BadPort : public NetworkError { }; try { Socket s; s.connect(“konark”, 80); String buf = s.readInput(); } catch ( HostNotFound ) { } catch ( BadPort ) { } catch ( NetworkError ) { }
  • 26. PCCP, FPGDST 2003 26 © CDAC (Formerly NCST) Exception Resolution  Exceptions can be caught by a handler using the base class rather than the exact class  Semantics for handler catching and naming are identical to that of a function  Pointers and references can be used to avoid losing information
  • 27. PCCP, FPGDST 2003 27 © CDAC (Formerly NCST) Exception Matching  Order of handlers is important  Handlers are tried in order
  • 28. PCCP, FPGDST 2003 28 © CDAC (Formerly NCST) Example class NetworkError { }; class HostNotFound : public NetworkError { }; class BadPort : public NetworkError { }; try { Socket s; s.connect(“konark”, 80); String buf = s.readInput(); } catch ( NetworkError ) { } catch ( HostNotFound ) { } catch ( BadPort ) { } never caught
  • 29. PCCP, FPGDST 2003 29 © CDAC (Formerly NCST) Re-throwing an Exception  Handler can re-throw an exception  throw used without an argument  Exception re-thrown is original exception thrown
  • 30. PCCP, FPGDST 2003 30 © CDAC (Formerly NCST) Example void f1() { try { Object toThrow("‘new object'"); throw toThrow; } catch ( Object o ) { throw; // re-throw exception } } try { f1(); } catch ( Object err ) { . . .} original exception caught
  • 31. PCCP, FPGDST 2003 31 © CDAC (Formerly NCST) Exception specifications  Set of exceptions that a function may throw, can be specified as a part of the function declaration. void f(int a) throw(Exception1, ..) {…  It guarantees that function will not throw any other types of exception.  If during execution function does something that tries to abrogate the guarantee. The attempt will be transferred to std::unexpected()  Std::unexpected => std::terminate()
  • 32. PCCP, FPGDST 2003 32 © CDAC (Formerly NCST) Exception Specification & ptr to ()  An exception specification can also be provided in the declaration of a pointer to function.  Assignment for pointers to function with exception specification: Example: void func1(int) throw(); void func2(int)throw(string,exceptionType1); pf = func1; /* okay: func1() is more restrictive */ pf = func2; /* error: func2() is less restrictive */ void (*pf)(int) throw (string);
  • 33. PCCP, FPGDST 2003 33 © CDAC (Formerly NCST) Standard exceptions Standard exception thrown by language: Name Thrown by Bad_alloc Bad_cast Bad_typeid Bad_exception new dynamic_cast typeid Exception- specificficat ion
  • 34. PCCP, FPGDST 2003 34 © CDAC (Formerly NCST) Standard Exceptions  Thrown by the Standard Library Name Thrown by out_of_range invalid_argument overflow_error ios_base::failure at() bitset<>::operator[]() bitset constructor bitset<>::to_ulong() ios_base::clear
  • 35. PCCP, FPGDST 2003 35 © CDAC (Formerly NCST) Standard exception class class exception { Public: exception() throw(); exception(const exception&) throw(); exception& operator =(const exception&) throw(); virtual ~exception(); virtual const char* what() const throw(); Private: // };
  • 36. PCCP, FPGDST 2003 36 © CDAC (Formerly NCST) Exception Class Hierarchy exception run time error logic_error bad_alloc bad_exception ios_base::failure bad_typeid bad_cast range_error underflow_ error overflow_error Invalid_arguments out_of_range domain_ error lenth_error
  • 37. PCCP, FPGDST 2003 37 © CDAC (Formerly NCST) Benefits  Provides an alternative to traditional techniques of error checking  Explicit separation of error handling and regular code possible  More regular style of error handling  Simplifies reuse
  • 38. PCCP, FPGDST 2003 38 © CDAC (Formerly NCST) Summary  Exception handling mechanism is better  try, catch for exception handling  Multiple exceptions can be handled  Exception hierarchy can be created

Editor's Notes

  • #3: The object/method may notice the abnormality and issue a message. This is probably the least disastrous reaction a program may show. The program in which the abnormality is observed may decide to stop its intended task, returning an errorcode to its caller. This is a great example of postponing decisions: now the calling function is faced with a problem. Of course the calling function may act similarly, by passing the error-code up to its caller. The program may decide that things are going out of hand, and may call exit() to terminate the program completely. A tough way to handle a problem.