In my project codding i have to use a try catch method to find the function execution status.
try
{
//sample code
//calling functions
function1();
function2();
//........
}
catch(//need to catch exception)
{
return failure;
}
My requirement is that i have to catch all the exceptions that thrown from the try block
i have two options here,
catch(...)
catch(std::exception)
I think the first one will catch all the exceptions. And the second one, std::exception is the base class for all other exception classes in my program
class MyException : public std::exception
{
// All the exceptions that i have use is derived from this class
}.
Which is better and more efficient.
Is the both method works same way. Help me and suggest any method
In this case, you'd work your way through the types which may be thrown in the following order:
catch (MyException& e) {
...
}
catch (std::exception& e) {
...
}
catch (...) {
...
}
This way, you can handle the specific errors/types first, and then fall back on the weak (or untyped) handlers when the preceding handlers do not match.
Which is better and more efficient.
The order I recommended is best for handling by type. IMO, efficiency is not a concern in this scenario because correctness takes precedence and hopefully exceptions are thrown only under exceptional circumstances.
Always keep your specification as focused as possible so that you catch those that you know could be thrown, and catch derived exceptions (more specialised) before base ones:
try
{
// Some stuff
}
catch (Derived& e)
{
// Deal with specifics of Derived
}
catch (Base& e)
{
// Deal with general case of Base
}
Never use catch(...) except at the very top of your program stack (and certainly not in libraries.) When you do this, you cannot be sure about what caused the exception and therefore you cannot necessarily rely on things that you normaly would (such as memory management etc.)
I would suggest you to catch the specified exceptions only and use the catch(...) only in the main function. In my opinion the better way to use the exceptions is to implement one exception per module so each class will throw the specific exception related with the module of the class also different exceptions may be handled with a different way so I believe that
catch(const ExceptionType1& e){
}catch(const ExceptionType2& e){
}
is the better solution, also some other developer just reading this code will see which kind of exceptions could be thrown and handled....
Related
I have a library I use that throws something, but I don't know how to identify what was being thrown.
Sample code to reproduce this:
int main()
{
char* memoryOutOfBounds;
unsigned __int64 bigNumber = -1;
try {
throw std::string("Test");
memoryOutOfBounds = new char[bigNumber];
}
catch (const std::bad_alloc& ex)
{
printf("Exception: %s\n", ex.what());
}
catch (...)
{
printf("Unknown.\n");
}
return 0;
}
The new char[bigNumber] will throw a std::bad_alloc, which is derived from std::exception and will enter the first branch. The other one, throw std::string will enter the second branch. How can I check the object that was thrown? I tried with a catch(void*) in the hopes to catch any object in memory, but that did not happen, so how can I find out what was thrown and from there debug what may have caused this?
catch (...) {}
means: Catch absolute everything that was thrown and drop it. This is only meant as a safeguard, so no exceptions fly out of the window and bring down the whole house. (Aka: Application Termination by Unhandled Exception")
There is no way to tell what was thrown in here.
But as you actually know that an std::string can be thrown, you can catch it in a
catch (const std::string& s) {}
block. You do need to know what (type) was thrown whenever you want to catch exceptions.
However, most libraries which add their own types for exceptions will have them inherit from std::exception. Therefore a
catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
block should get them.
If they do not inherit from std::exception and/or block the what() method, it is a stupid way to make the usage of their library extra difficult.
However, somewhere in the documentation of the library the exception throwing behaviour should be explained.
Edit : I think that Point 1. under "How should I design my exception classes" on the Boost Error Handling document is something every library developer should keep in mind. And hopefully the developers of your library did keep that principle in mind. ;-)
There really is no standard C++ way to query any information about the exception that is being thrown. Which is unfortunate, because the runtime has that information in order to match catch blocks. But there is just no access to that information in user code.
If it's purely for research purposes, like just finding out what the type is because the library you're using lacks documentation, you could use std::current_exception() to get a std::exception_ptr object that stores (or references) the thrown exception internally. This type is implementation-defined, but your debugger might happen to provide you with enough information.
#include <exception>
void foo()
{
try
{
function_that_throws();
}
catch(...)
{
std::exception_ptr p = std::current_exception();
// break here and inspect 'p' with a debugger
}
}
This stackoverflow post would be helpful-
C++ get description of an exception caught in catch(...) block
Since C++11 you can capture the current exception with a pointer:
std::exception_ptr p; // default initialization is to nullptr
try {
throw std::string("Test");
}
catch(...)
{
p = std::current_exception();
}
I have searched a lot for the differences between these two types of handlers, but everyone said that catch(...) is a generic handler which catches everything.
I could not find any exception that one of them can handle and the other cannot. Even divide by zero, creates an exception that both of them cannot handle (floating point exception).
Can anyone give me a sample and explain clearly their difference? Which one of them should I use?
Is there any exception that catch(...) can handle while catch(exception& ex) cannot?
Yes, any exception that is not, or not derived from, std::exception will not be caught by catch(exception&). For example; throw 42; will be caught by catch(...), but not catch(exception&).
A throw exception(); can be caught by either; the first handler is chosen. The catch(...) should be the last handler.
Even divide by zero, creates an exception which both of them cannot handle (floating point exception)...
Visual Studio has two modes of exception handling; synchronous (/EHsc) and asynchronous (/EHa). For the synchronous handling, both catch(...) and catch(exception&) will only catch C++ exceptions; i.e. those thrown with a throw xyz;. For the asynchronous handling, access violations etc. can be caught with catch(...).
VS also offers a function _set_se_translator() that can be used to "translate" or handle the Win32 exceptions. Typically the function is used to translate the Win32 exception to a C++ exception (derived from exception) that can be handled by a catch(exception&).
A sample of what the translation could look like (some detail is omitted for brevity);
struct seh_exception : std::runtime_error {
//...
};
struct access_violation : seh_exception {
//...
};
struct unspecified_seh_exception : seh_exception {
//...
};
void translation_function(unsigned int code, ::EXCEPTION_POINTERS* info)
{
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
throw access_violation();
break;
// more cases for other exception codes
};
throw unspecified_seh_exception();
}
Which one of them should I use?
You should use the one that you can do something with. If all exceptions result in the same handling by your code, then use catch(...). If your code needs to handle the exceptions separately, then you should have a handler for each exception that is expected.
Sure, any exception that is of a type that doesn't have std::exception as its base class will not be caught by catch(std::exception& ex).
For example,
struct foo {};
throw foo();
will be caught by catch (...), and not by std::exception.
You are allowed to throw pretty much anything (e.g an int), and catch(...) will catch anything. catch(exception&) will only catch exception or derived types.
catch(...){} is catching all exceptions. catch(std::exception& ex){} is catching all exceptions with std::exception as a base class.
http://en.cppreference.com/w/cpp/language/try_catch
In C++, why would you want to rethrow an exception. Why not let the current catch block handle the exception. For what reasons would you rethrow an exception to another try/catch block?
An exception is thrown when a function cannot meet its contract (what it promises the caller it will do). When a function calls another function that throws an exception, there are four main approaches to how it might respond:
Catch the exception and handle it. This should only be done if the function is able to meet its contract despite the exception being thrown. If it catches the exception but fails to meet its contract, it is hiding a problem from the calling code.
Allow the exception to propagate. This should be done if the exception cannot be handled by this function (that is, the function is unable to meet its contract because the exception has been thrown), and if the exception exposes the appropriate information to the calling code.
Catch the exception, do some clean-up and/or add extra info, and rethrow it. This should be done if the exception cannot be handled by this function, but it needs to do some cleaning up before propagating it. It can also provide extra information to help with handling/debugging the exception (I often think of the programmer as the very last exception handler).
Catch the exception and throw a different exception (perhaps wrapping the original). This should be done if the exception cannot be handled by this function, but a different exception better expresses the problem to the calling code.
Why not let the current catch block handle the exception. For what reasons would you rethrow an exception to another try/catch block?
The idea behind exceptions is that you throw them at the error site and handle them down the stack, where you have enough information to handle the error.
Conversely, there are cases when you must do something in case of an error, but still don't know how to handle the error (this is the case when you rethrow).
Example:
void connect_and_notify(int connection_data)
{
try
{
create_network_connection(connection_data); // defined somewhere else
notify("connection open"); // same (notify event listeners)
}
catch(const std::runtime_error&)
{
notify("connection failed");
throw;
}
}
Client code:
void terminal_app_controller()
{
try
{
connect_and_notify(1);
}
catch(const std::runtime_error& err)
{
std::cerr << "Connection failed;\n";
exit(1); // this is usually bad bad code but whatever
}
}
void ongoing_server_controller()
{
bool connected = false;
int connection = 1;
while(!connected)
{
try
{
connect_and_notify(1);
connected = true;
}
catch(const std::runtime_error&)
{
connection++;
}
}
}
In the two usage scenarios, the error is handled differently (connect_and_notify has no way of knowing that, but still, on a failed connection it must notify listeners).
Each function has a different policy to handle the exception and this means different catch blocks.
I very much dislike anything like
catch (std::exception&) {
... // do some cleanup
throw;
}
RAII is the correct solution to that problem. Even:
catch (std::exception&) {
... // do some logging here
throw;
}
can be handled with RAII, although it is less intuitive.
BUT - where I have rethrown is any situation where 3rd-part (or vendor-supplied) code throws "generic" exceptions with state. For example, when logging telematics messages to a database, I know that I often receive duplicate copies of the same message. Each message has a unique ID - so a primary key violation in my DB is an "innocent" error that should be silently ignored.
Unfortunately, the DB framework we use doesn't throw a specific exception for PK violations - so we need to catch the generic dbexception and check what its reason code is to decide what to do. Hence:
catch (db::exception& e) {
if (e.reason != db::exception::reason::pk_violation)
throw;
}
Also, piwi mentioned internal state. An example would be
for (;;) {
try {
...
}
catch (some_exception& e) {
if (retry_count > 3)
throw;
}
}
Remember: If you are going to rethrow, always catch by reference to avoid slicing the exception object. (You should usually catch by ref anyway, but it is even more important when rethrowing)
Suppose I have two inheritance hierarchies I'm dealing with in C++. One inherits from std::exception (new hierarchy), and the other inherits from Exception (legacy C++ Builder VCL base exception class). If I call code that may throw either type of exception, I have to 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 each caller needs to have all these catch clauses to try to get every last type of exception, since C++ has no one true, enforced exception base class you can use as a catch-all (e.g. System.Exception class in C#). (catch (...) is a non-starter since you don't have a way of knowing what you caught, and some dangerous system exceptions, like access violations, could be caught as well which are better left untrapped.)
I would like to wrap these "legacy" exceptions into a class in the std::exception hierarchy. This concept of wrapping 3rd-party exceptions into your own exception system isn't entirely unprecedented. For example, the .NET Framework wraps broad sets of errors in other systems (e.g. COMException). Ideally, I'd like to see something like this:
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;
}
Understandably, the exception is never caught - it would be asking quite a bit of magic from the compiler for it to catch it.
Is there a solution that might be similar to the above for wrapping a legacy exception, and achieves these goals?
One "catch" clause or similar, so that general exception handling logic need only be written once.
Logic for converting from one exception type to another must be centralized.
Avoids macros if possible.
No use of lambda functions.
Having worked with BC++Builder I have met the same problem, and macros seemed to be the only solution at the time.
The "cleaner" (hum...) solution is probably a "double-try-catch": the inner try-catch converts your legacy exception into a standard class, and the outer one actually handles the exception.
I don't have the code at hand (it's been years) but basically it boils down to:
#define DTRY try { try
#define DCATCH catch (Exception& e) { throw LegacyException(e); } } catch
DTRY {
...
}
DCATCH(std::exception& e) {
// handle the exception
}
Yes I know it's ugly, but when I worked with Borland I didn't find anything better. Fact is, at that time Borland was awfully non-standard and I have no idea how it evolved since, maybe you can do better nowadays. Hope this helps anyway.
In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?
catch (...)
{
// Handle exceptions not covered.
}
Important considerations:
A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.
catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.
Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the RAII pattern if you choose this route.
You don't want to be using catch (...) (i.e. catch with the ellipsis) unless you really, definitely, most provable have a need for it.
The reason for this is that some compilers (Visual C++ 6 to name the most common) also turn errors like segmentation faults and other really bad conditions into exceptions that you can gladly handle using catch (...). This is very bad, because you don't see the crashes anymore.
And technically, yes, you can also catch division by zero (you'll have to "StackOverflow" for that), but you really should be avoiding making such divisions in the first place.
Instead, do the following:
If you actually know what kind of exception(s) to expect, catch those types and no more, and
If you need to throw exceptions yourself, and need to catch all the exceptions you will throw, make these exceptions derive from std::exception (as Adam Pierce suggested) and catch that.
If you are on windows and need to handle errors like divide by zero and access violation you can use a structured exception translator. And then inside of your translator you can throw a c++ exception:
void myTranslator(unsigned code, EXCEPTION_POINTERS*)
{
throw std::exception(<appropriate string here>);
}
_set_se_translator(myTranslator);
Note, the code will tell you what the error was. Also you need to compile with the /EHa option (C/C++ -> Code Generatrion -> Enable C/C++ Exceptions = Yes with SEH Exceptions).
If that doesn't make sense checkout the docs for [_set_se_translator](http://msdn.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx)
If catching all exceptions - including OS ones - is really what you need, you need to take a look at your compiler and OS. For example, on Windows you probably have "__try" keyword or compiler switch to make "try/catch" catch SEH exceptions, or both.
Make all your custom exception classes inherit from std::exception, then you can simply catch std::exception. Here is some example code:
class WidgetError
: public std::exception
{
public:
WidgetError()
{ }
virtual ~WidgetError() throw()
{ }
virtual const char *what() const throw()
{
return "You got you a widget error!";
}
};
In C++, the standard does not define a divide-by-zero exception, and implementations tend to not throw them.
You can, of course, use catch (...) { /* code here */ }, but it really Depends On What You Want To Do. In C++ you have deterministic destructors (none of that finalisation rubbish), so if you want to mop up, the correct thing to do is to use RAII.
For example. instead of:
void myfunc()
{
void* h = get_handle_that_must_be_released();
try { random_func(h); }
catch (...) { release_object(h); throw; }
release_object(h);
}
Do something like:
#include<boost/shared_ptr.hpp>
void my_func()
{
boost::shared_ptr<void> h(get_handle_that_must_be_released(), release_object);
random_func(h.get());
}
Create your own class with a destructor if you don't use boost.
You can use catch(...) to catch EVERYTHING, but then you don't get a an object to inspect, rethrow, log, or do anything with exactly. So... you can "double up" the try block and rethrow into one outer catch that handles a single type. This works ideally if you define constructors for a custom exception type that can build itself from all the kinds you want to group together. You can then throw a default constructed one from the catch(...), which might have a message or code in it like "UNKNOWN", or however you want to track such things.
Example:
try
{
try
{
// do something that can produce various exception types
}
catch( const CustomExceptionA &e ){ throw e; } \
catch( const CustomExceptionB &e ){ throw CustomExceptionA( e ); } \
catch( const std::exception &e ) { throw CustomExceptionA( e ); } \
catch( ... ) { throw CustomExceptionA(); } \
}
catch( const CustomExceptionA &e )
{
// Handle any exception as CustomExceptionA
}
If I recall correctly (it's been a while since I've looked at C++), I think the following should do the trick
try
{
// some code
}
catch(...)
{
// catch anything
}
and a quick google(http://www.oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html) seems to prove me correct.