BIT153 ยท 2082 ยท 5 marks
Write a program to handle division by zero exception using try, catch, and throw.
Write a program to handle division by zero exception using try, catch, and throw. [5]
Object Oriented ProgrammingChapter 10: Exception Handling and File I/OException handling definition and purpose
Handling Division by Zero Exception Using try, catch, and throw
Concept
In C++, exception handling uses three keywords:
- try - block of code that may throw an exception
- throw - used to throw/raise an exception when an error occurs
- catch - block that handles the thrown exception
Program
#include <iostream>
using namespace std;
// Function to perform division
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw "Division by zero is not allowed!"; // throw exception
}
return (double)numerator / denominator;
}
int main() {
int a, b;
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denominator: ";
cin >> b;
try {
// Code that may cause exception
double result = divide(a, b);
cout << "Result: " << a << " / " << b << " = " << result << endl;
}
catch (const char* msg) {
// Handle the exception
cout << "Exception caught: " << msg << endl;
}
cout << "Program continues after exception handling." << endl;
return 0;
}
Sample Output
Case 1: Normal Division
Enter numerator: 10
Enter denominator: 2
Result: 10 / 2 = 5
Program continues after exception handling.
Case 2: Division by Zero
Enter numerator: 10
Enter denominator: 0
Exception caught: Division by zero is not allowed!
Program continues after exception handling.
Explanation
| Keyword | Role in Program |
|---|---|
throw | Throws a string message when denominator is 0 |
try | Wraps the call to divide() that may fail |
catch | Catches the thrown string and displays the error |
- When denominator is not zero, the division executes normally.
- When denominator is zero,
throwtransfers control directly to thecatchblock, skipping the remainingtryblock. - After the
catchblock executes, the program continues normally, demonstrating graceful error handling.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.