Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining exception type after the exception is caught?

Is there a way to determine the exception type even know you caught the exception with a catch all?

Example:

try {    SomeBigFunction(); } catch(...) {    //Determine exception type here } 
like image 334
Brian R. Bondy Avatar asked Feb 18 '09 17:02

Brian R. Bondy


People also ask

What happens after catching an exception?

It is up to you to ensure that the application is recovered into a stable state after catching the exception. Usually it is achieved by "forgetting" whatever operation or change(s) produced the exception, and starting afresh on a higher level.

How does Python determine exception type?

To get exception information from a bare exception handler, you use the exc_info() function from the sys module. The sys. exc_info() function returns a tuple that consists of three values: type is the type of the exception occurred.

Which catches any type of exception?

Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.

What happens if an exception is thrown but not caught?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.


1 Answers

Short Answer: No.

Long Answer:

If you derive all your exceptions from a common base type (say std::exception) and catch this explicitly then you can use this to get type information from your exception.

But you should be using the feature of catch to catch as specific type of exception and then working from there.

The only real use for catch(...) is:

  • Catch: and throw away exception (stop exception escaping destructor).
  • Catch: Log an unknwon exception happend and re-throw.

Edited: You can extract type information via dynamic_cast<>() or via typid() Though as stated above this is not somthing I recomend. Use the case statements.

#include <stdexcept> #include <iostream>  class X: public std::runtime_error  // I use runtime_error a lot {                                   // its derived from std::exception     public:                         // And has an implementation of what()         X(std::string const& msg):             runtime_error(msg)         {} };  int main() {     try     {         throw X("Test");     }     catch(std::exception const& e)     {         std::cout << "Message: " << e.what() << "\n";          /*          * Note this is platform/compiler specific          * Your milage may very          */         std::cout << "Type:    " << typeid(e).name() << "\n";     } } 
like image 187
Martin York Avatar answered Sep 19 '22 23:09

Martin York