Can catch() be written to convert from one object type to another?
c++, exception, try-catch
Solution
No, that cannot work. User-defined conversions are not taken into consideration when matching a thrown object to a handler. Per paragraph 15.3/3 of the C++11 Standard:
A handler is a match for an exception object of type `E` if
The handler is of type `cv T` or `cv T&` and `E` and `T` are the same type (ignoring the top-level cv-qualifiers), or
the handler is of type `cv T` or `cv T&` and `T` is an unambiguous public base class of `E`, or
the handler is of type `cv T` or `const T&` where `T` is a pointer type and `E` is a pointer type that can be converted to `T` by either or both of
a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes
a qualification conversion
the handler is of type `cv T` or `const T&` where `T` is a pointer or pointer to member type and `E` is `std::nullptr_t`.
Problem
Given this code, where `A` is in a 3rd-party library, and `B` is code I wrote: ``` class A {...}; class B { public: B( const A &a ); ... }; try { A a(...); throw a; } catch ( const B &b ) { // ...do stuff with B, like log the details to a file... } ``` If an object `A` is thrown, then my `catch B` is skipped. I was hoping since `B` has a constructor that takes an `A` object, that this might work. Is there something I can do to make this work, or do I have to modify all `catch` clauses to handle catching both `A` and `B`?