Can you wrap one hierarchy of exception inheritance in another? - Or, another clean way to handle this?

Suppose I have two inheritance hierarchies that I deal with in C ++. One inherits from std::exception(the new hierarchy), and the other inherits from Exception(the base exception class of the C ++ Builder VCL class). If I call code that can throw any type of exception, I must write code like this:

try {
    // do stuff....
    Function1();
    Function2();
} catch (std::exception &ex) {
    std::cout << "STL exception caught: " << ex.what() << std::endl;
} catch (Exception &ex) {
    std::cout << "Legacy exception caught: " << ex.Message.c_str() << std::endl;
} catch (SomeOtherVendorLibraryException &ex) {
    // etc.
}

The problem is that every caller must have all these catch tricks in order to try to get every last type of exception, since C ++ does not have a single true, forced base exception class that you can use as catch-all (e.g. , System.Exceptionclass in C #). (It catch (...)’s not a starter, since you don’t have a way to find out what you caught, and some dangerous system exceptions, such as access violations, can also be caught that are better left unchecked).

"" std::exception. . ,.NET Framework (, COMException). - :

class LegacyException : public std::runtime_error {
public:
    // construct STL exception from legacy exception
    LegacyException(const Exception &ex) : std::runtime_error(ex.Message.c_str()) {}
};

try {
    // In reality, this throw will happen in some function we have no control over.
    throw Exception("Throwing legacy exception!");
} catch (std::exception &ex) {
    // Ideally, the compiler would use the LegacyException constructor
    // to cast the thrown Exception to a LegacyException, which ultimately
    // inherits from std::exception.
    std::cout << ex.what() << std::endl;
}

, - , .

, ?

  • "catch" , .
  • .
  • , .
  • -.
+5
1

B++ Builder, , , , .

"" (hum...), , " ": try-catch , - .

( ), :

#define DTRY  try { try
#define DCATCH catch (Exception& e) { throw LegacyException(e); } } catch

DTRY {
   ...
}
DCATCH(std::exception& e) {
    // handle the exception
}

, , Borland, . , Borland , , , , . , .

+2
source

All Articles