Exception Handling in C++
Introduction
Exception handling deals with runtime errors gracefully using try, throw, and catch blocks, preventing abrupt program termination.
Flow Diagram
Fig 5.1 β Control flows from try β throw β catch β resume.
Definition
Exception Handling: Mechanism to transfer control to a handler when an abnormal condition occurs during execution.
C++ Code Example
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
try {
if (b == 0) throw b;
cout << "Result: " << a/b << endl;
} catch (int x) {
cout << "Cannot divide by zero!" << endl;
}
return 0;
}Multiple Catch
You can have multiple catch blocks for different types, plus catch(...) to catch all.
catch (int i) { /* int */ }
catch (float f) { /* float */ }
catch (...) { /* all others */ }Important Questions
Short Questions
- What is an exception?
- Difference between throw and catch?
- What is catch(...) ?
- Can we have multiple catch blocks?
Long Questions
- Explain try-throw-catch with an example.
- Discuss multiple catch and catch-all.
MCQ Practice
1. Keyword to raise an exception is:
- throw
- raise
- catch
- try
Answer: throw.
2. A try block must be followed by:
- throw
- catch
- return
- exit
Answer: catch.
3. catch(...) catches:
- Any exception
- Only int
- Only char
- Nothing
Answer: any exception.
4. Exception handling prevents:
- Compile errors
- Abrupt termination
- Syntax errors
- Linker errors
Answer: abrupt termination.
5. Which is NOT a part of exception handling?
- try
- throw
- catch
- finally
Answer: finally (not in C++).
Quick Revision
- try: guarded block.
- throw: raise exception.
- catch: handle by type.
- catch(...) catches all.