

Use throw only to signal an error (which means specifically that the function couldn’t do what it advertised, and establish its postconditions).What shouldn’t I use exceptions for?Ĭ++ exceptions are designed to support error handling. In C programs, longjmp() is an additional hazard. If the “use f” part of old_fct throws an exception – or simply does a return – the file isn’t closed. This contrasts to the common unsafe usage: void old_fct(const char* s)įILE* f = fopen(s,"r") // open the file named "s" If the “use f” part of fct() throws an exception, the destructor is still invoked and the file is properly closed. If (v.bad()) // here File_handle's destructor closes the file At least, we would have to write: vector v(100000) // needs to allocate memory For example, in the case of ofstream, your output simply disappears if you forget to check that the open operation succeeded.

The vector or ofstream (output file stream) constructor could either set the variable into a “bad” state (as ifstream does by default) so that every subsequent operation fails. Ofstream os("myfile") // needs to open a file Imagine that we did not have exceptions, how would you deal with an error detected in a constructor? Remember that constructors are often invoked to initialize/construct objects in variables: vector v(100000) // needs to allocate memory That’s the basis of RAII (Resource Acquisition Is Initialization), which is the basis of some of the most effective modern C++ design techniques: A constructor’s job is to establish the invariants for the class (create the environment in which the member functions are to run) and that often requires the acquisition of resources, such as memory, locks, files, sockets, etc.

Consider an error detected in a constructor how do you report the error? You throw an exception. That way, your code gets messy and it becomes hard to ensure that you have dealt with all errors (think “spaghetti code” or a “rat’s nest of tests”).įirst of all there are things that just can’t be done right without exceptions. But what’s wrong with “good old errno and if-statements”? The basic answer is: Using those, your error handling and your normal code are closely intertwined. What good can using exceptions do for me? The basic answer is: Using exceptions for error handling makes your code simpler, cleaner, and less likely to miss errors.

Exceptions and Error Handling Why use exceptions?
