- Asked 2/10
- 2074 Chaitra · 5 marks
- 2072 Kartik · 5 marks
Handling multiple exceptions
Short answer
A try block can throw different exception types. Multiple catch blocks are written in order; the first matching type handles it. A catch(...) block, placed last, catches any remaining exception.
With suitable example explain how multiple exceptions are handled in C++.
A program can have more than one kind of error. When a try block may throw different types of exceptions, several catch blocks are written after it, one for each type. The thrown value is compared with the catch handlers in order, and the first one with a matching type runs; the others are skipped. A catch(...) handler, placed last, catches any remaining exception.
Syntax:
try { ... }
catch (type1 x) { ... }
catch (type2 y) { ... }
catch (...) { ... } // default handler (must be last)
Example
#include <iostream>
using namespace std;
void test(int x) {
try {
if (x == 0) throw 0; // int
else if (x == 1) throw 'a'; // char
else if (x == 2) throw 1.5; // double
else if (x == 3) throw "string"; // const char*
cout << "No exception\n";
}
catch (int e) { cout << "Caught int\n"; }
catch (char e) { cout << "Caught char: " << e << endl; }
catch (double e) { cout << "Caught double: " << e << endl; }
catch (...) { cout << "Caught some other exception\n"; }
}
int main() {
for (int i = 0; i <= 4; i++)
test(i);
return 0;
}
Output
Caught int
Caught char: a
Caught double: 1.5
Caught some other exception
No exception
throw "string" has type const char*, which matches none of the first three handlers, so catch(...) handles it.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Date of birth validation with exceptions · Object Oriented Programming, chapter 10
- Importance of error handling · Object Oriented Analysis and Design, chapter 4 · asked 2×
- Interrupts and handling with single INTR pin · Microprocessor, chapter 5