Exception Handling: Multiple Exception Handlers
What is it?
C++ Exception Handling Multiple Exception Handlers can handle multiple exceptions that might occur within the same try
block. This feature is useful when multiple exceptions can occur within the same code block.
Syntax
The syntax of using multiple exception handlers is as follows:
try {
// Some code that might throw exceptions
} catch (exception_type1 e1) {
// Code to handle exception_type1
} catch (exception_type2 e2) {
// Code to handle exception_type2
}
Where,
exception_type1
andexception_type2
are the types of exceptions that can be thrown.e1
ande2
are the objects that hold the information from the thrown exceptions.
How to use it
To use multiple exception handlers, follow the below steps:
- Write the code that might throw exceptions within a
try
block. - Add multiple
catch
blocks to handle different exceptions. - Each
catch
block should have its own exception type and object to store the thrown exception's information.
Program code snippet example
#include <iostream>
#include <fstream>
using namespace std;
int main() {
try {
// Opening a non-existent file to read
ifstream file("nonExistentFile.txt");
// Trying to read from the file
int x;
file >> x;
// Closing the file
file.close();
} catch (const ifstream::failure& e) {
cout << "Error opening or reading file: " << e.what() << endl;
} catch (const exception& e) {
cout << "An error occurred: " << e.what() << endl;
}
return 0;
}
Output:
Error opening or reading file: basic_ios::clear: iostream error
In the above code example, we use multiple exception handlers to handle two different types of exceptions that might occur when opening and reading a file. The first catch
block handles ifstream::failure
that might occur when accessing a non-existent file. The second catch
block handles any other type of exception that might occur.
Chain a catch
expression to a try
-catch
block.