7 Function Templates And Exception Handling

Object Oriented Programming · Unit 7 · 4 hrs

Function Templates and Exception Handling

Exam-focused notes for Function Templates and Exception Handling (Object Oriented Programming, CSC166): what the TU syllabus asks and how it has actually been tested, with 9 solved past questions from this unit.

Function Templates and Exception Handling in short

This unit covers C++'s generic programming facility, function and class templates, including templates with more than one type parameter and how a template class can be a base class for further inheritance, and then its exception handling facility built on try, throw and catch.

Function Templates and Exception Handling: notes

Function templates

A function template defines a family of functions that work with any data type, written once with the actual type left as a parameter, so the same code serves int, float, double or any other type without being duplicated for each. The general form is:

template <class T>
T functionName(T param1, T param2) {
    // function body written generically in terms of T
}

class here can equally be written as typename; both mean exactly the same thing in a template parameter list. The compiler generates an actual function for a specific type only when the template is called with that type, a process called instantiation.

#include <iostream>
using namespace std;

template <class T>
T larger(T n1, T n2) {
    return (n1 > n2) ? n1 : n2;
}

int main() {
    cout << larger(3, 7) << endl;         // int version, prints 7
    cout << larger(3.5, 2.1) << endl;     // double version, prints 3.5
    cout << larger('a', 'z') << endl;     // char version, prints z
    return 0;
}

Function templates with multiple arguments

A template may take more than one generic type, listed as a comma separated list inside the angle brackets:

#include <iostream>
using namespace std;

template <class T1, class T2>
void showPair(T1 a, T2 b) {
    cout << a << " and " << b << endl;
}

int main() {
    showPair(5, 3.14);       // T1 = int, T2 = double
    showPair("Roll", 12);    // T1 = const char*, T2 = int
    return 0;
}

What this unit covers

  • Function templates
  • Function templates with multiple arguments
  • Class templates
  • templates and inheritance
  • Exceptional Handling (Try, throw and catch)
  • Use of exceptional handling

Exceptional Handling

2080 · 5 marks

List any two operators that cannot be overloaded. Write a program to handle the possible exception in taking 'age' as input. Here the exception must be thrown in the input is negative or greater than 200. [5]

Show solved answer

Answer

Two Operators That Cannot Be Overloaded

The following operators cannot be overloaded in C++:

OperatorName
::Scope Resolution Operator
?:Ternary (Conditional) Operator

Other examples include: . (member access), .* (pointer to member), sizeof.


Program to Handle Exception for Invalid Age Input

The program throws an exception if the entered age is negative or greater than 200.

#include <iostream>
using namespace std;

// Custom Exception Class for Age
class AgeException {
private:
    string message;
public:
    AgeException(string msg) {
        message = msg;
    }
    string getMessage() {
        return message;
    }
};

// Function to validate and return age
int getAge(int age) {
    if (age < 0) {
        throw AgeException("Invalid age: Age cannot be negative.");
    }
    else if (age > 200) {
        throw AgeException("Invalid age: Age cannot be greater than 200.");
    }
    return age;
}

int main() {
    int age;
    cout << "Enter age: ";
    cin >> age;

    try {
        int validAge = getAge(age);
        cout << "Valid Age entered: " << validAge << endl;
    }
    catch (AgeException e) {
        cout << "Exception caught: " << e.getMessage() << endl;
    }

    return 0;
}

Sample Output

Case 1: Valid Input

Enter age: 25
Valid Age entered: 25

Case 2: Negative Age

Enter age: -5
Exception caught: Invalid age: Age cannot be negative.

Case 3: Age Greater Than 200

Enter age: 250
Exception caught: Invalid age: Age cannot be greater than 200.

Explanation

  • The AgeException class is a user-defined exception class that stores an error message.
  • The getAge() function throws an AgeException object when the age is invalid (negative or > 200).
  • In main(), the try block calls getAge() and the catch block handles the thrown exception by printing the error message.
  • This approach separates error-handling code from normal program code, which is one of the key uses of exception handling as stated in the notes.
Open this answer on its own page →

2078 · 5 marks

What is exception? Why exception handling is better to use? Explain exception handling with try.... catch by using suitable example. [5]

Show solved answer

Exception Handling in C++ with try...catch

What is an Exception?

An exception is an unusual or abnormal event (error condition) that occurs during the execution of a program and disrupts the normal flow of the program's instructions. Examples include division by zero, file not found, invalid memory access, and array index out of bounds.

Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.


Why is Exception Handling Better to Use?

Without Exception HandlingWith Exception Handling
Errors cause abrupt program terminationProgram can handle errors gracefully
Error-checking code mixed with normal codeClean separation of error-handling code
Difficult to maintain and readEasier to maintain and debug
No mechanism to propagate errorsErrors can be propagated up the call stack

Key benefits:

  • Keeps the normal logic and error-handling logic separate
  • Prevents abnormal program termination
  • Allows recovery from runtime errors
  • Makes code more readable and maintainable

Three Keywords of Exception Handling

  1. try -- Defines a block of code to be tested for errors while it is being executed. A block that may raise an exception is placed inside a try block (called protected code).
  2. throw -- Used to throw (signal) an exception when a problem is detected.
  3. catch -- Catches the exception thrown by the try block and handles it. The catch keyword indicates the catching of an exception.

Syntax

try {
    // protected code
    // code that might throw an exception
    throw exception_value;
}
catch (type variable) {
    // exception handler
    // code to handle the exception
}

A try/catch block is referred to as protected code.


Example: Division by Zero

#include <iostream>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero is not allowed!";  // throw exception
    }
    return a / b;
}

int main() {
    int x = 10, y = 0;

    try {
        // protected code
        int result = divide(x, y);
        cout << "Result: " << result << endl;
    }
    catch (const char* msg) {
        // exception handler
        cout << "Exception caught: " << msg << endl;
    }

    cout << "Program continues after exception handling." << endl;

    return 0;
}

Output:

Exception caught: Division by zero is not allowed!
Program continues after exception handling.

How it Works (Step by Step)

Step 1: divide(10, 0) is called inside the try block
Step 2: Inside divide(), b == 0, so throw is executed
Step 3: Control immediately transfers to the matching catch block
Step 4: catch(const char* msg) catches the thrown string
Step 5: Error message is displayed
Step 6: Program continues normally after the catch block

Summary

KeywordRole
tryEncloses code that might cause an exception
throwSignals that an exception has occurred
catchHandles the exception and prevents program crash

Exception handling ensures that even when errors occur at runtime, the program can handle them gracefully and continue execution rather than crashing abruptly.

Open this answer on its own page →

2076 · 5 marks

How can define catch statement that can catch any type of exception? Illustrate the use of multiple catch statement with example. [5]

To catch any type of exception regardless of its type, we use the ellipsis (...) inside the catch statement's parentheses. This acts as a catch-all handler and must be placed as the last catch block. Syntax: The catch(...) block will handle every exception that is thrown inside the corresponding ...

Open this answer on its own page →

2075 · 5 marks

Explain how exceptions are used for handling C++ error in a systematic and OOP-oriented way with the design that includes multiple exceptions. [5]

Exception handling is a mechanism in C++ that allows a program to detect and respond to runtime errors in a structured, OOP-oriented way. As stated in the notes, it is used "to develop a reliable and robust system" and "prevents the separation of error handling code from the normal program code."...

Open this answer on its own page →

Function templates with multiple arguments

2079 · 5 marks

Write a program to implement function template with multiple arguments. [5]

A function template allows writing a generic function that works with different data types. When a template uses more than one parameter, it is called a function template with multiple arguments. Syntax: --- --- --- Template Call T1 T2 Description ------------ display(10, 20) int int Both argumen...

Open this answer on its own page →

Class templates

2078 · 5 marks

When class templates are useful? How can you define a class that can implement stack with integer as well as sack of strings? Illustrate with example. [5]

Class templates are useful when: - You need to create a class that performs the same operations on different data types (int, float, string, etc.) - You want to avoid code duplication by writing a single generic class instead of separate classes for each data type - You want type safety along wit...

Open this answer on its own page →

Function templates

2076 · 5 marks

What is meant by template? How can you define function template to return maximum of two integers, floats, or characters? Explain with example. [5]

A template is a feature in C++ that allows writing generic programs. A template defines a blueprint for a function or class that can work with any data type. Instead of writing separate functions for each data type (int, float, char, etc.), a single template function can handle all of them. The c...

Open this answer on its own page →

2075 · 5 marks

Create a function called swaps() that interchanges the values of the two arguments sent to it (pass these arguments by reference), make the function into a template, so it can be used with all numerical data types (char, int, float, and so on), write a main() program to exercise the function with several types. [5]

A function template allows writing a single generic function that works with multiple data types. The compiler automatically generates the appropriate version of the function for each data type used. Syntax: Passing arguments by reference (using &) means the function works directly on the origina...

Open this answer on its own page →

2080.1 · 5 marks

Explain function template overloading with suitable example. [5]

Function template overloading means defining more than one template function with the same name but with different numbers of parameters or different logic, so that the compiler selects the appropriate version based on the arguments passed at the call site. It combines the concept of function tem...

Open this answer on its own page →