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.
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 answerHide answer
Answer
Two Operators That Cannot Be Overloaded
The following operators cannot be overloaded in C++:
| Operator | Name |
|---|---|
:: | 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
AgeExceptionclass is a user-defined exception class that stores an error message. - The
getAge()function throws anAgeExceptionobject when the age is invalid (negative or > 200). - In
main(), thetryblock callsgetAge()and thecatchblock 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.
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 answerHide 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 Handling | With Exception Handling |
|---|---|
| Errors cause abrupt program termination | Program can handle errors gracefully |
| Error-checking code mixed with normal code | Clean separation of error-handling code |
| Difficult to maintain and read | Easier to maintain and debug |
| No mechanism to propagate errors | Errors 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
- 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).
- throw -- Used to throw (signal) an exception when a problem is detected.
- 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
| Keyword | Role |
|---|---|
try | Encloses code that might cause an exception |
throw | Signals that an exception has occurred |
catch | Handles 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.
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]
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]
Function templates with multiple arguments
2079 · 5 marks
Write a program to implement function template with multiple arguments. [5]
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]
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]
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]
2080.1 · 5 marks
Explain function template overloading with suitable example. [5]
Make Unit 7 stick
Practice CSC166 with flashcards & quizzes