I understand that exception handler catch(...) in C++ handles any type of exception. I am wondering what happens if it has to handle an exception that is of some class type - is the object of that class passed to this handler by reference or by value?
This is the code that could help in understanding this. When the exception of type B is thrown in "Inner try", an unnamed temporary object of class B is created with the default constructor of class B. When I run this program, copy constructor of class B doesn't get called at all, and this unnamed temporary object of class B is destroyed only after executing "Outer try 3", which means that object was propagated backwards all the way to the "Outer try 3". So my guess is that objects are passed by reference to the catch(...) handler, but I wanted to see if this is correct reasoning.
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << "Default constructor of class A" << endl;
}
A(const A& a) {
cout << "Copy constructor of class A" << endl;
}
A(A&& a) noexcept {
cout << "Move constructor of class A" << endl;
}
~A() {
cout << "Destructor of class A" << endl;
}
};
class B {
public:
B() {
cout << "Default constructor of class B" << endl;
}
B(const B& b) {
cout << "Copy constructor of class B" << endl;
}
B(B&& b) noexcept {
cout << "Move constructor of class B" << endl;
}
~B() {
cout << "Destructor of class B" << endl;
}
};
int main() {
try {
try {
try {
try {
throw A();
}
catch (A a) {
cout << "Inner try" << endl;
throw B();
}
}
catch (...) {
cout << "Outer try 1" << endl;
throw;
}
}
catch (...) {
cout << "Outer try 2" << endl;
throw;
}
}
catch (...) {
cout << "Outer try 3" << endl;
}
}