0% found this document useful (0 votes)
23 views38 pages

10 - Exceptions and Templates - Update - 15may2018

The document discusses exceptions in C++ programming, including how to throw and catch exceptions using keywords like throw and try/catch, and provides examples of using exceptions to handle errors; it also covers function templates which allow functions to work with different data types, and class templates which allow classes to be defined using type parameters.

Uploaded by

Arif Istiaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views38 pages

10 - Exceptions and Templates - Update - 15may2018

The document discusses exceptions in C++ programming, including how to throw and catch exceptions using keywords like throw and try/catch, and provides examples of using exceptions to handle errors; it also covers function templates which allow functions to work with different data types, and class templates which allow classes to be defined using type parameters.

Uploaded by

Arif Istiaq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

10: EXCEPTIONS AND

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

 Indicate that something unexpected has occurred or been


detected.

 Allow program to deal with the problem in a controlled


manner.

 Can be as simple or complex as program design requires.


Terminology

 Exception: object or value that signals an error 


exceptional circumstance  run-time errors.

 Throw an exception: send a signal that an error has


occurred.

 Catch/ Handle an exception: process the exception;


interpret the signal.
Keywords

 throw: send a signal that an error has occurred.

 try: followed by a block {}, is used to invoke code that


throws an exception.

 catch: followed by a block {}, is used to detect and


process exceptions thrown in preceding try block. Takes a
parameter that matches the type thrown.
Flow of Control

 A function that throws an exception is called from within a


try block.

 If the function throws an exception:


 The function terminates and the try block is immediately
exited.
 A catch block to process the exception is searched for in the
source code immediately following the try block.

 If a catch block is found that matches the exception


thrown, it is executed. If no catch block that matches the
exception is found, the program terminates.
Example 1a: Using throw

//Function that throws an exception


int totalDays(int days, int weeks)
{
if ((days < 0) || (days > 7))
throw “Invalid number of days!";
//the argument to throw is a literal c-string
else
return (7 * weeks + days);
}
Example 1b: Using try…catch
int main(){
int totDays,days, weeks;

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?

 try block is entered. totalDays function is called to.

 If 1st parameter is between 0 and 7, total number of days is


returned and catch block is skipped over (no exception
thrown).

 If exception is thrown, function and try block are exited,


catch blocks are scanned for 1st one that matches the data
type of the thrown exception. catch block executes.
Additional Notes:
Dealing with string exceptions
 You can throw different types of string exceptions.
 A literal string
 C string
 C++ string

Throwing a literal
c-string

Throwing a c-string
variable

Throwing a string
object (c++ string)
Additional Notes:
Dealing with string exceptions

 Then, catch the exceptions accordingly

Catching a literal c-
string exception

Catching a c-string
exception

Catching a c++
string exception
Example 2a: Using try…catch

Correction:

catch (const char *exceptionString)


Example 2b: Using throw
Example 2: What Happens in the
try…catch Construct?

Correction:

catch (const char


*exceptionString)
Example 2: What Happens if No
Exception is Thrown?

Correction:

catch (const char


*exceptionString)
Exception Not Caught?

 An exception will not be caught if


 it is thrown from outside of a try block
 there is no catch block that matches the data type of the thrown
exception

 If an exception is not caught, the program will terminate.


Exceptions and Objects

 An exception class can be defined in a class and thrown as an


exception by a member function.

An exception class may have:


 no members: used only to signal an error
 members: pass error data to catch block.

 A class can have more than one exception class.


Example 3a
Example 3b
Example 3c
Example 3d:
Sample Output
Additional Notes:
C++ Built-in Exception Classes

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

Members of the class


exception

Source:
http://www.cplusplus.com/doc/tutorial/exceptions/
Example

Creating a new exception


class by extending the class
exception
Then , catching exceptions
is done as usual
Function Templates
Introduction

 Function template: a pattern for a function that can work


with many data types.

 When written, parameters are left for the data types.

 When called, compiler generates code for specific data types


in function call.
Example 4a
template <class T> Template prefix
T times10(T num) Generic type
{
return 10 * num; Type parameter
}

What gets generated when What gets generated when


times10 is called with an int: times10 is called with a double:
int times10(int num) double times10(double num)
{ {
return 10 * num; return 10 * num;
} }
Example 4b
template <class T>
T times10(T num)
{
return 10 * num;
}

Call a template function in the usual manner:


int ival = 3;
double dval = 2.55;
cout << times10(ival); // displays 30
cout << times10(dval); // displays 25.5
Notes 1
 Function templates can be overloaded.

 Each template must have a unique parameter list.

template <class T>


T sumAll(T num) ...
template <class T1, class T2>
T1 sumall(T1 num1, T2 num2) ...
Notes 2

 All data types specified in template prefix must be used in


template definition.

 Function calls must pass parameters for all data types


specified in the template prefix.

 Like regular functions, function templates must be defined


before being called.
Where to Start
When Defining Templates
 Templates are often appropriate for multiple functions that
perform the same task with different parameter data types.

Develop function using usual data types first, then


convert to a template:
 add template prefix
 convert data type names in the function to a type
parameter (i.e., a T type) in the template.
Class Templates
Introduction

 Classes can also be represented by templates.

 When a class object is created, type information is supplied


to define the type of data members of the class.

 Unlike functions, classes are instantiated by supplying the


type name (int, double , string , etc.) at object
definition.
Example 5a
template <class T>
class Grade
{
private:
T score;
public:
Grade(T);
void setGrade(T);
T getGrade()
};
Example 5b

• Pass type information to class template when


defining objects:
Grade<int> testList[20];
Grade<double> quizList[20];

• Use as ordinary objects once defined

You might also like