Exception Handling in C++

Unit 5 Β· Topic 5.1⏱ 10 min readπŸ“Š 1 diagram❓ 5 MCQs

Introduction

Exception handling deals with runtime errors gracefully using try, throw, and catch blocks, preventing abrupt program termination.

Flow Diagram

Exception handling flow: try throw catch resume

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

  1. What is an exception?
  2. Difference between throw and catch?
  3. What is catch(...) ?
  4. Can we have multiple catch blocks?

Long Questions

  1. Explain try-throw-catch with an example.
  2. 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.