10 - Exceptions and Templates - Update - 15may2018
10 - Exceptions and Templates - Update - 15may2018
TEMPLATES
Programming Technique II
(SCSJ1023)
Adapted from Tony Gaddis and Barret Krupnow (2016), Starting out with
C++: From Control Structures through Objects
Exceptions
Introduction to Exceptions
cout << "Enter no. of. days and no. of. weeks =>";
cin >> days >> weeks;
try{
totDays = totalDays(days, weeks);
cout << "Total days: " << totDays;
}
catch (const char *msg){ Correction:
cout << "Error: " << msg;
catch (const char *msg)
}
return 0;
}
//code in the try-block is called protected code
//code in the catch-block is called exception handler
Example 1: What Happens?
Throwing a literal
c-string
Throwing a c-string
variable
Throwing a string
object (c++ string)
Additional Notes:
Dealing with string exceptions
Catching a literal c-
string exception
Catching a c-string
exception
Catching a c++
string exception
Example 2a: Using try…catch
Correction:
Correction:
Correction:
Source:
https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
Example
An exception of bad_alloc
will be thrown by the
command new when there is
not enough memory left.
Example (continued)
An exception of
bad_alloc was caught
Additional Notes:
Creating a New Exception Class by Extending the
class exception
An exception class can also be defined outside of a class by extending the
built-in classes e.g., the class exception
Source:
http://www.cplusplus.com/doc/tutorial/exceptions/
Example