CSC166 ยท 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.
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]
Object Oriented ProgrammingChapter 7: Function Templates and Exception HandlingExceptional Handling
Quick answer
The program throws an exception if the entered age is negative or greater than 200.
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
#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.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.