- Asked 4/10
- 2074 Chaitra · 3 marks
- 2070 Chaitra · 3 marks
- 2069 Chaitra · 5 marks
- 2068 Chaitra · 3 marks
Exception handling constructs
Short answer
try block encloses code that may throw an exception. throw raises an exception with a value. catch block handles a matching exception type; catch(...) catches any. Control resumes after the last catch if exception handled.
Explain about all Exception Handling constructs in C++ (try, catch, throw) with example.
An exception is a run-time error (divide by zero, array index out of range, memory failure). C++ handles exceptions with three keywords.
try– a block of code in which exceptions may occur. If an exception is thrown inside it, control leaves the block at once.throw– raises (throws) an exception by giving a value or object of some type:throw 10;,throw "error";,throw MyError();catch– a handler placed immediately after the try block. It catches an exception of a matching type and handles it.catch(...)catches any type.
Syntax:
try {
// code that may throw
throw exception_value;
}
catch (type1 arg) {
// handle type1
}
catch (...) {
// handle everything else
}
Flow
try block --throw--> search matching catch --> handler runs
| | |
no exception no match: terminate() continue after
(catch skipped) last catch block
Example
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter a and b: ";
cin >> a >> b;
try {
if (b == 0)
throw "Division by zero"; // throw
cout << "a/b = " << a / b << endl;
}
catch (const char *msg) { // catch
cout << "Error: " << msg << endl;
}
cout << "Program continues\n";
return 0;
}
For b = 0 the output is Error: Division by zero followed by Program continues.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Exception handling over conventional error handling · Object Oriented Programming, chapter 10
- Re-throwing an exception · Object Oriented Programming, chapter 10
- Exception handling: OO vs conventional · Object Oriented Analysis and Design, chapter 4