You are on page 1of 22

Module 37

Intructors: Abir
Das and
Sourangshu
Bhattacharya
Module 37: Programming in C++
Objectives &
Outlines Exceptions (Error handling in C++): Part 2
Exceptions in
C++
try-throw-catch
Exception Scope
(try)
Exception Arguments Intructors: Abir Das and Sourangshu Bhattacharya
(catch)
Exception Matching Department of Computer Science and Engineering
Exception Raise Indian Institute of Technology, Kharagpur
(throw)
Advantages {abir, sourangshu}@cse.iitkgp.ac.in
std::exception
Module Summary
Slides taken from NPTEL course on Programming in Modern C++

by Prof. Partha Pratim Das

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 1


Module Objectives

Module 37
Intructors: Abir
Das and
Sourangshu
• Understand the Error handling in C++
Bhattacharya

Objectives &
Outlines

Exceptions in
C++
try-throw-catch
Exception Scope
(try)
Exception Arguments
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 2


Module Outline

Module 37
Intructors: Abir
Das and
Sourangshu
Bhattacharya
1 Exceptions in C++
Objectives & try-throw-catch
Outlines

Exceptions in
Exception Scope (try)
C++ Exception Arguments (catch)
try-throw-catch
Exception Scope Exception Matching
(try)
Exception Arguments Exception Raise (throw)
(catch)
Exception Matching Advantages
Exception Raise
(throw)
std::exception
Advantages
std::exception
Module Summary
2 Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 3


Expectations

Module 37
Intructors: Abir
Das and
Sourangshu
• Separate Error-Handling code from Normal code
Bhattacharya
• Language Mechanism rather than of the Library
Objectives &
Outlines
• Compiler for Tracking Automatic Variables
Exceptions in
C++
• Schemes for Destruction of Dynamic Memory
try-throw-catch
Exception Scope
• Less Overhead for the Designer
(try)
Exception Arguments
• Exception Propagation from the deepest of levels
(catch)
Exception Matching • Various Exceptions handled by a single Handler
Exception Raise
(throw)
Advantages
std::exception
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 4


Error Handling Dynamics: C and C++
Header Caller Callee
Module 37
Intructors: Abir C Scenario
Das and
Sourangshu
Bhattacharya #include <stdio.h> int main() { jmp_buf jbuf;
#include <stdbool.h> if (setjmp(jbuf) == 0) { void g() {
Objectives & #include <setjmp.h> printf("g() called\n"); bool error = false;
Outlines g(); printf("g() started\n");
Exceptions in printf("g() returned\n"); if (error)
C++ } longjmp(jbuf, 1);
try-throw-catch else printf("g() failed\n"); // On longjmp printf("g() ended\n");
Exception Scope return 0; return;
(try)
} }
Exception Arguments
(catch)
Exception Matching C++ Scenario
Exception Raise
(throw)
Advantages
#include <iostream> int main() { class Excp: public exception {};
std::exception
#include <exception> try { void g() {
using namespace std; cout << "g() called\n"; bool error = false;
Module Summary
g(); cout << "g() started\n";
cout << "g() returned\n"; if (error)
} throw Excp();
catch (Excp&) { cout << "g() failed\n"; } cout << "g() ended\n";
return 0; return;
} }

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 5


try-throw-catch

Module 37
Intructors: Abir Caller Callee
Das and
Sourangshu
Bhattacharya
int main() { class Excp: public exception {};
try { void g() {
Objectives &
cout << "g() called\n"; bool error = false;
Outlines g(); cout << "g() started\n";
cout << "g() returned\n"; if (error)
Exceptions in
C++ } throw Excp();
try-throw-catch catch (Excp&) { cout << "g() failed\n"; } cout << "g() ended\n";
Exception Scope return 0; return;
(try) } }
Exception Arguments
(catch)
Exception Matching
Exception Raise
(1) g() called
(throw) (2) g() successfully returned
Advantages
std::exception
g() called
Module Summary
g() started
g() ended
g() returned

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 6


try-throw-catch

Module 37 Caller Callee


Intructors: Abir
Das and
Sourangshu
int main() { class Excp: public exception {};
Bhattacharya try { class A {};
cout << "g() called\n"; void g() { A a;
Objectives & g(); bool error = true;
Outlines cout << "g() returned\n"; cout << "g() started\n";
Exceptions in } if (error)
C++ catch (Excp&) { cout << "g() failed\n"; } throw Excp();
try-throw-catch return 0; cout << "g() ended\n";
Exception Scope } return;
(try)
Exception Arguments
}
(catch)
Exception Matching
Exception Raise (1) g() called
(throw)
(2) Exception raised
Advantages
(3) Stack frame of g() unwinds and destructor of a called
std::exception
(4) Remaining execution of g() and cout skipped
Module Summary (5) Exception caught by catch clause
(6) Normal flow continues

g() called
g() started
g() failed
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 7
Exception Flow
#include <iostream> void f() { MyClass f_a;
Module 37
Intructors: Abir #include <exception> try { g();
Das and using namespace std; bool okay = true; // Not executed
Sourangshu class MyException: public exception { };
Bhattacharya }
class MyClass { public: ~MyClass() { } }; // Catches exception from Line 3
void h() { MyClass h_a; catch (MyException) { cout << "MyException\n"; }
Objectives &
Outlines //throw 1; // Line 1 // Catches exception from Line 4
//throw 2.5; // Line 2 catch (exception) { cout << "exception\n"; }
Exceptions in
C++
//throw MyException(); // Line 3 // Catches exception from Line 5 & passes on
try-throw-catch //throw exception(); // Line 4 catch (...) { throw; }
Exception Scope //throw MyClass(); // Line 5 } // Stack unwind, f_a.~MyClass() called
(try) } // Stack unwind, h_a.~MyClass() called
Exception Arguments
(catch)
// Passes on all exceptions int main() {
Exception Matching
void g() { MyClass g_a; try { f();
Exception Raise try { h(); bool okay = true; // Not executed
(throw) bool okay = true; // Not executed }
Advantages
} // Catches exception from Line 5
std::exception
// Catches exception from Line 1 catch (...) { cout << "Unknown\n"; }
Module Summary catch (int) { cout << "int\n"; }
// Catches exception from Line 2 cout << "End of main()\n";
catch (double) { cout << "double\n"; } }
// Catches exception from Line 3-5 & passes on
catch (...) { throw; }
} // Stack unwind, g_a.~MyClass() called

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 8


try Block: Exception Scope

Module 37 • try block


Intructors: Abir
Das and ◦ Consolidate areas that might throw exceptions
Sourangshu
Bhattacharya
• function try block
Objectives &
Outlines
◦ Area for detection is the entire function body
Exceptions in • Nested try block
C++
try-throw-catch ◦ Semantically equivalent to nested function calls
Exception Scope
(try)
Exception Arguments
(catch)
Function try Nested try
Exception Matching void f() try {
Exception Raise
(throw) try { try { throw E(); }
Advantages
std::exception
throw E(); catch (E& e) { }
Module Summary } }
catch (E& e) { catch (E& e1) {
} }
Note: The usual curly braces for the
function scope are not to be put here
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 9
catch Block: Exception Arguments

Module 37
Intructors: Abir
Das and
Sourangshu
• catch block
Bhattacharya
◦ Name for the Exception Handler
Objectives & ◦ Catching an Exception is like invoking a function
Outlines
◦ Immediately follows the try block
Exceptions in
C++ ◦ Unique Formal Parameter for each Handler
try-throw-catch
Exception Scope
◦ Can simply be a Type Name to distinguish its Handler from others
(try)
Exception Arguments
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 10


try-catch: Exception Matching

Module 37
Intructors: Abir
Das and
Sourangshu
• Exact Match
Bhattacharya
◦ The catch argument type matches the type of the thrown object
Objectives &
Outlines
▷ No implicit conversion is allowed
Exceptions in • Generalization / Specialization
C++
try-throw-catch ◦ The catch argument is a public base class of the thrown class object
Exception Scope
(try)
• Pointer
Exception Arguments
(catch)
Exception Matching
◦ Pointer types – convertible by standard conversion
Exception Raise
(throw)
Advantages
std::exception
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 11


try-catch: Exception Matching

Module 37
Intructors: Abir
Das and
Sourangshu
• In the order of appearance with matching
Bhattacharya
• If Base Class catch block precedes Derived Class catch block
Objectives &
Outlines
◦ Compiler issues a warning and continues
Exceptions in
◦ Unreachable code (derived class handler) ignored
C++
try-throw-catch • catch(...) block must be the last catch block because it catches all exceptions
Exception Scope
(try) • If no matching Handler is found in the current scope, the search continues to find a
Exception Arguments
(catch) matching handler in a dynamically surrounding try block
Exception Matching
Exception Raise
(throw)
◦ Stack Unwinds
Advantages
std::exception
• If eventually no handler is found, terminate() is called
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 12


throw Expression: Exception Raise

Module 37
Intructors: Abir
Das and
Sourangshu
• Expression is treated the same way as
Bhattacharya
◦ A function argument in a call or the operand of a return statement
Objectives &
Outlines
• Exception Context
Exceptions in ◦ class Exception { };
C++
try-throw-catch • The Expression
Exception Scope
(try)
◦ Generate an Exception object to throw
Exception Arguments
(catch)
Exception Matching
▷ throw Exception();
Exception Raise
(throw) ◦ Or, Copies an existing Exception object to throw
Advantages
std::exception ▷ Exception ex;
Module Summary ▷ ...
▷ throw ex; // Exception(ex);
• Exception object is created on the Free Store

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 13


throw Expression: Restrictions

Module 37
Intructors: Abir
Das and
Sourangshu
• For a UDT Expression
Bhattacharya
◦ Copy Constructor and Destructor should be supported
Objectives &
Outlines
• The type of Expression cannot be an incomplete type or a pointer to an incomplete type
Exceptions in ◦ No incomplete type like void, array of unknown size or of elements of incomplete
C++
try-throw-catch type, Declared but not Defined struct / union / enum / class Objects or
Exception Scope
(try)
Pointers to such Objects
Exception Arguments
(catch)
◦ No pointer to an incomplete type, except void*, const void*, volatile void*,
Exception Matching const volatile void*
Exception Raise
(throw)
Advantages
std::exception
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 14


(re)-throw: Throwing Again?

Module 37
Intructors: Abir
Das and
Sourangshu
• Re-throw
Bhattacharya
◦ catch may pass on the exception after handling
Objectives & ◦ Re-throw is not same as throwing again!
Outlines

Exceptions in
C++
Throws again Re-throw
try-throw-catch
Exception Scope try { ... } try { ... }
(try)
Exception Arguments catch (Exception& ex) { catch (Exception& ex) {
(catch)
Exception Matching // Handle and // Handle and
Exception Raise
(throw)
... ...
Advantages
std::exception
// Raise again // Pass-on
Module Summary
throw ex; throw;
// ex copied // No copy
// ex destructed // No Destruction
} }

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 15


Advantages

Module 37
Intructors: Abir
Das and
Sourangshu
• Destructor-savvy:
Bhattacharya
◦ Stack unwinds; Orderly destruction of Local-objects
Objectives &
Outlines
• Unobtrusive:
Exceptions in ◦ Exception Handling is implicit and automatic
C++
try-throw-catch ◦ No clutter of error checks
Exception Scope
(try) • Precise:
Exception Arguments
(catch) ◦ Exception Object Type designed using semantics
Exception Matching
Exception Raise
(throw)
• Native and Standard:
Advantages
std::exception
◦ EH is part of the C++ language
Module Summary ◦ EH is available in all standard C++ compilers

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 16


Advantages

Module 37
Intructors: Abir
Das and
Sourangshu
• Scalable:
Bhattacharya
◦ Each function can have multiple try blocks
Objectives & ◦ Each try block can have a single Handler or a group of Handlers
Outlines
◦ Each Handler can catch a single type, a group of types, or all types
Exceptions in
C++
try-throw-catch • Fault-tolerant:
Exception Scope
(try) ◦ Functions can specify the exception types to throw; Handlers can specify the
Exception Arguments
(catch) exception types to catch
Exception Matching
Exception Raise
◦ Violation behavior of these specifications is predictable and user-configurable
(throw)
Advantages
std::exception
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 17


Exceptions in Standard Library: std::exception

Module 37
Intructors: Abir
Das and All objects thrown by components of the standard library are derived from this class.
Sourangshu
Bhattacharya Therefore, all standard exceptions can be caught by catching this type by reference.
Objectives &
class exception {
Outlines public:
Exceptions in
C++ exception() throw();
try-throw-catch exception(const exception&) throw();
Exception Scope
(try) exception& operator=(const exception&) throw();
Exception Arguments
(catch) virtual ~exception() throw();
Exception Matching
Exception Raise virtual const char* what() const throw();
(throw)
Advantages }
std::exception
Module Summary Sources: std::exception and std::exception in C++11, C++14, C++17 & C++20

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 18


Exceptions in Standard Library: std::exception

Module 37
Intructors: Abir
Das and
Sourangshu
Bhattacharya

Objectives &
Outlines

Exceptions in
C++
try-throw-catch
Exception Scope
(try)
Exception Arguments
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

Sources: Standard Library Exception Hierarchy

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 19


Exceptions in Standard Library: std::exception

Module 37
Intructors: Abir • logic error: Faulty logic like violating logical preconditions or class invariants (may be
Das and
Sourangshu preventable)
Bhattacharya
◦ invalid argument: An argument value has not been accepted
Objectives &
Outlines
◦ domain error: Situations where the inputs are outside of the domain for an operation
Exceptions in
◦ length error: Exceeding implementation defined length limits for some object
C++ ◦ out of range: Attempt to access elements out of defined range
try-throw-catch
Exception Scope • runtime error: Due to events beyond the scope of the program and can not be easily
(try)
Exception Arguments
predicted
(catch)
Exception Matching
◦ range error: Result cannot be represented by the destination type
Exception Raise
(throw)
◦ overflow error: Arithmetic overflow errors (Result is too large for the destination type)
Advantages ◦ underflow error: Arithmetic underflow errors (Result is a subnormal floating-point value)
std::exception
Module Summary
• bad typeid: Exception thrown on typeid of null pointer
• bad cast: Exception thrown on failure to dynamic cast
• bad alloc: Exception thrown on failure allocating memory
• bad exception: Exception thrown by unexpected handler
Sources: std::exception and std::exception in C++11, C++14, C++17 & C++20
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 20
Exceptions in Standard Library: std::exception:
C++98, C++11, C++14, C++17 & C++20
Module 37
Intructors: Abir • logic error • bad typeid
Das and
Sourangshu ◦ invalid argument • bad cast
Bhattacharya ◦ domain error ◦ bad any cast (C++17)
Objectives &
◦ length error • bad weak ptr (C++11)
Outlines ◦ out of range • bad function call (C++11)
Exceptions in
◦ future error (C++11) • bad alloc
C++
• bad optional access (C++17) ◦ bad array new length (C++11)
try-throw-catch
Exception Scope
• runtime error • bad exception
(try)
Exception Arguments
◦ range error • ios base::failure (until C++11)
(catch) ◦ overflow error • bad variant access (C++17)
Exception Matching
Exception Raise
◦ underflow error
(throw) ◦ regex error (C++11)
Advantages
◦ system error (C++11)
std::exception
Module Summary
▷ ios base::failure (C++11)
▷ filesystem::filesystem error (C++17)
◦ txtion (TM TS)
◦ nonexistent local time (C++20)
◦ ambiguous local time (C++20)
◦ format error (C++20)
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 21
Module Summary

Module 37
Intructors: Abir
Das and
Sourangshu
• Discussed exception (error) handling in C++
Bhattacharya
• Illustrated try-throw-catch feature in C++ for handling errors
Objectives &
Outlines
• Demonstrated with examples
Exceptions in
C++
try-throw-catch
Exception Scope
(try)
Exception Arguments
(catch)
Exception Matching
Exception Raise
(throw)
Advantages
std::exception
Module Summary

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 22

You might also like