Multiple catch Blocks

Multiple catch Blocks for Different Exception Types in C++

C++Intermediate
C++
#include <iostream>
#include <stdexcept>
using namespace std;

void processNumber(int num) {
    if (num < 0) {
        throw invalid_argument("Number cannot be negative");
    }
    if (num > 100) {
        throw out_of_range("Number exceeds maximum value");
    }
    if (num == 0) {
        throw runtime_error("Number cannot be zero");
    }
    
    cout << "Processing number: " << num << endl;
}

int main() {
    int numbers[] = {5, -3, 150, 0, 50};
    
    for (int num : numbers) {
        try {
            processNumber(num);
        } catch (const invalid_argument& e) {
            cout << "Invalid argument: " << e.what() << endl;
        } catch (const out_of_range& e) {
            cout << "Out of range: " << e.what() << endl;
        } catch (const runtime_error& e) {
            cout << "Runtime error: " << e.what() << endl;
        } catch (...) {
            cout << "Unknown error occurred" << endl;
        }
    }
    
    return 0;
}

Output

Processing number: 5
Invalid argument: Number cannot be negative
Out of range: Number exceeds maximum value
Runtime error: Number cannot be zero
Processing number: 50

This program teaches you how to use Multiple catch Blocks in C++. Multiple catch blocks allow handling different exception types with specific error handling logic. This enables precise error management based on the type of exception thrown.


1. What This Program Does

The program demonstrates multiple catch blocks:

  • Handling different exception types
  • Specific catch blocks for each type
  • Catch-all block for unknown exceptions
  • Processing multiple values with error handling

Multiple catch blocks enable type-specific error handling.


2. Header Files Used

  1. #include <iostream>

    • Provides cout and cin for input/output operations.
  2. #include <stdexcept>

    • Provides standard exception classes.

3. Understanding Multiple Catch Blocks

Multiple Catch Concept:

  • Different catch blocks for different types
  • Checked in order (top to bottom)
  • First matching catch executes
  • More specific before general

Catch Order:

  • Specific exceptions first
  • General exceptions last
  • catch(...) as catch-all
  • Order matters!

4. Standard Exception Types

Common Types:

  • invalid_argument: invalid parameter
  • out_of_range: value out of range
  • runtime_error: runtime error
  • logic_error: logic error

How it works:

  • Each type for specific errors
  • Provides what() method
  • Inherits from exception
  • Standard error handling

5. Throwing Different Exceptions

Throwing Specific Types:

if (num < 0) { throw invalid_argument("Number cannot be negative"); } if (num > 100) { throw out_of_range("Number exceeds maximum value"); }

How it works:

  • Throw specific exception types
  • Each type for specific error
  • Provides error message
  • Caught by matching catch

6. Catching Specific Exceptions

Multiple Catch Blocks:

catch (const invalid_argument& e) { cout << "Invalid argument: " << e.what() << endl; } catch (const out_of_range& e) { cout << "Out of range: " << e.what() << endl; } catch (const runtime_error& e) { cout << "Runtime error: " << e.what() << endl; }

How it works:

  • Each catch handles specific type
  • Checked in order
  • First match executes
  • Others skipped

7. Catch-All Block

Using catch(...):

catch (...) { cout << "Unknown error occurred" << endl; }

How it works:

  • Catches any exception type
  • Must be last catch block
  • No exception value access
  • Safety net for unexpected errors

8. When to Use Multiple Catch Blocks

Best For:

  • Different error types
  • Type-specific handling
  • Precise error messages
  • Different recovery strategies
  • Comprehensive error handling

Example Scenarios:

  • Input validation (multiple checks)
  • File operations (different errors)
  • Network operations (various failures)
  • Database operations (different errors)

9. Important Considerations

Catch Order:

  • More specific first
  • General last
  • catch(...) always last
  • Wrong order = wrong catch

Exception Hierarchy:

  • Standard exceptions inherit from exception
  • Can catch base class
  • More general catch catches derived
  • Understand inheritance

Error Messages:

  • Use what() method
  • Provides error description
  • Help with debugging
  • Inform users

10. return 0;

This ends the program successfully.


Summary

  • Multiple catch blocks: handle different exception types with specific logic.
  • Catch blocks checked in order, first matching catch executes.
  • Standard types: invalid_argument, out_of_range, runtime_error, logic_error.
  • catch(...): catch-all for any exception type, must be last.
  • Always catch more specific exceptions before general ones.
  • Understanding multiple catch blocks enables precise error handling.
  • Essential for comprehensive error management and type-specific recovery.

This program is fundamental for learning advanced exception handling, understanding exception types, and preparing for robust error management in C++ programs.