Decoupling exceptions from log formatting - c++

In my API I have a small exception hierarchy, derived from std::exception. I have a base class Exception, which provides an error code, file, line, and function. Other more specific exceptions are derived from Exception. For example, one derived class adds a platform-specific error code, as well as a field that identifies which function returned the error code. This is like a simplified version of system_error, but I can't use C++11 features (I'm stuck working with VS2005, and no Boost).
I need to log these exceptions with my logging class. I want the exceptions to be logged in a certain format. After reading various forums online, and reading Boost's Error and Exception Handling Guidelines, I don't think the what function of each exception, or any other virtual function within Exception, is the appropriate place to format the exception for logging. Therefore my what functions just return the name of the class.
When catching exceptions, I often want to catch very general exceptions, usually std::exception, and pass it to the logger. I don't want to catch individual exceptions very often because I am trying to prevent exceptions from escaping the API (the public portion of my API is in C), and there may be several exceptions that could occur. I want to avoid code like:
try { /* blah */ }
catch {DerivedException const& ex) { logger.log(ex); }
...
catch {Exception const& ex) { logger.log(ex); }
So in my logging class, my log function accepts a std::exception argument. It then uses typeid to compare the parameter to the various exception classes, casting to the appropriate type and then calling a logging function specialized for that type of exception. This is essentially the same technique described in this other post.
I use typeid instead of dynamic_cast because dynamic_cast can succeed for any valid downcast, and for code maintenance purposes, I really don't want the order of my if statements in the log function to matter.
So is this a decent design? It feels wrong to me using typeid like this, but I think I have valid reasons to do it. I haven't seen much exception handling "in the wild", since we primarily work with C, so I haven't seen too many approaches to the subject. Are there other ways to decouple exceptions from their log formatting that I should be aware of?
EDIT: What I decided to implement
I took the suggestion of using the visitor pattern, but adapted it to my situation. I wanted to catch std::exception, since those can be thrown as well as my own, but format the log message based on the exception type.
Each of my exception classes derive from my base Exception class and implement the virtual function accept. I created an ExceptionLogger class, which implements an ExceptionVisitor interface providing the visit functions.
The LogFile class has an instance of ExceptionLogger, as well as an overload of its log function that takes an std::exception parameter. In the log function, I try a dynamic_cast to my base type, Exception. If it succeeds, I call the accept function of the exception, otherwise I call the ExceptionLogger::visit(std::exception const&) function directly. Since std::exception doesn't implement my accept function, I needed the dynamic_cast so I could determine if more detailed logging was possible.
I chose to do this instead of a series of if statements checking typeid because:
It's a named design pattern that I can refer future maintainers to
If a maintainer adds a new exception deriving from my Exception base, but forgets to implement a new visit function for that exception, I will still get the logging that was implemented for the base Exception - a file, line number, and function.
If I had implemented the series of if statements, I would've had to fall back to the std::exception logging behavior, which is just to print out the results of what, or I could've tried a dynamic_cast to an Exception.
Of course I would still prefer a compiler error in this situation.

A simpler solution is to rethrow your exception in your central formatting method (see also this answer). You can then catch each exception type there and format it.
class Exception : public std::exception {};
class DerivedException : public Exception {};
void LogThrownException();
void DoSomething()
{
try
{
// Do something, might throw ...
}
catch (...)
{
LogThrownException();
}
}
void LogThrownException()
{
try
{
throw;
}
// Order is important to catch all derived types.
// Luckily the compiler should warn, if a type is hidden.
catch (DerivedException&)
{
std::cout << "DerivedException";
}
catch (Exception&)
{
std::cout << "Exception";
}
catch (std::exception&)
{
std::cout << "std::exception";
}
// ...
catch (...)
{
std::cout << "Unknown\n";
}
}

Related

Should exceptions have a flag/message, or should there be an exception type per error?

What are the best practices for an object that can throw an exception for many reasons?
For example if I have an assembler object that has its own exception type which derives from std::exception I can just set the message for what() to return. So I might do:
throw Asm::Exception("Duplicated function name");
throw Asm::Exception("Unknown instruction");
throw Asm::Exception("Wrong number of arguments");
But I'm wondering if:
throw Asm::DuplicateFunctionNameException();
throw Asm::UnknownInstructionException();
throw Asm::WrongNumberOfArgumentsException();
Is better? But I fear this could lead to many small objects that are essentially doing the same thing?
There is no "better" or "worse" approach. In fact, the two concepts are quite orthogonal. It really depends entirely on the desired functionality. You should choose depending on the answer to this question:
Do I need to be able to take different actions depending on the type of error throwing an exception?
If the answer is yes, then you're better off with different exception types:
try {
// stuff
} catch (Asm::DuplicateFunctionNameException& e) {
foo();
e.foo();
} catch (Asm::UnknownInstructionException& e) {
bar();
e.bar();
} catch (Asm::WrongNumberOfArgumentsException& e) {
baz();
e.baz();
}
Also note that each type of exception here could have members related to that particular error type.
If the answer is no, then you're OK with one type. Note that having different types doesn't prevent you from using different messages too.
throw Asm::Exception("Wrong number of arguments") already shows the problem, really. That exception should have the function name, actual arguments and expected arguments. Most exceptions won't need those fields, though. Logically, that means Asm::ArgCountException is a unique type.

Why Create An Exception Object That's Derived From stdexcept Header?

I was wondering why, and if so, to what advantage, you would create an exception object to throw exceptions, that derives from stdexcept header, such as an exception object that derives from runtime_error. The only thing i can really find on why you would do this, is so you can access the virtual function 'what' to obtain an appropriate error message. But can't you just pass the error message into runtime_error as an argument, and access 'what' anyway?
class divide_by_zero : public runtime_error
{
public:
divide_by_zero()
:runtime_error( "this is a runtime error" ) {};
}
if( ... )
{
throw divide_by_zero();
}
How is it any different than just doing something like...
if( ... )
{
throw std::runtime_error( "this is a runtime error" );
}
try
{
...
}
catch( std::runtime_error& e )
{
std::cerr << e.what()
<< std::endl;
}
Retired Ninja commented "You can catch the derived exception without catching all runtime_error exceptions.", and that's a key point. Your code might expect your divide_by_zero and want to ignore or log it, but not want a runtime_error thrown by say std::locale::locale to be hidden by that.
Further, note that if you used the same class and relied on comparisons of the what()-returned text, that would be very "fragile" as the throwing site generally expects to be able to reword the messages at whim to improve their clarity and utility. It's likely slower too.
If you use your own class, you can more easily enrich it later in a structured way, perhaps putting some details of the error, or processing underway when the error was encountered, into other variables that can be easily and reliably used. That can be contrasted with a post-facto move to embed new data in the text, which can confound current code with expectations about the message "style" and likely length (e.g. it might "blow out" a dialog box so it won't fit on screen cleanly), and having the text need to either become rigidly structured (e.g. moved to XML) or error-prone to parse....
It allows you to craft exceptions that are tailored to your specific API, while also adhering to the basic contract provided by std::exception. This allows you to provide a catch-all exception handler in main() or at the entry point to a DLL or .so file to prevent exceptions from leaking out of your program.

Proper use of exceptions in C++

In C++ should I use std::runtime_error to indicate some sort of error occurred, or should I create custom exceptions that inherit from std::runtime_error so I can better handle them.
For example, if I got input from the user somehow, which would be better:
if (inputInvalid)
{
throw std::runtime_error("Invalid input!");
}
Versus...
class invalid_input
: public std::runtime_error /* or should I inherit from std::exception? */
{
public:
invalid_input()
: std::runtime_error("Invalid input!")
{
};
};
-------------------------------------------------------
if (inputInvalid)
{
throw invalid_input();
}
Which is considered better use of exception handling/which if better practice?
I would only subclass a standard exception class in one of two cases:
None of the standard exception classes have names that describe the nature of my exception
My exception needs additional information than what can be found in a standard exception (i.e. a string describing the error).
Otherwise, there's not much point. Especially if others will have to interact with your code and wonder why there is a custom exception class that doesn't do anything a standard exception doesn't.
Always think about what you gain from inheriting std::runtime_error. Does it let you handle the error easier? In the example code it doesn't give any benefits so no there is no point in inheriting from std::runtime_error if all it does is the same thing. If you want to add more information than what std::runtime_error has then you might want to inherit and add those to your error class.
That will depend on the size of the project. If your working on something small and just need something quick and dirty, std:runtime_error is fine. But if your working on a big project you are going to want to create your own custom exceptions to help manage(through catches) all the different possibilities. Otherwise now if you made a catch, you would be catching EVERYTHING, which may be a problem if you need to catch multiple different things with different ways to handle them.
I would also read this:
Difference: std::runtime_error vs std::exception()
I would subclass std::exception() for your invalid_input class in the example you gave. Typically, a user input error is not considered a runtime error, you may want to catch it earlier, you may want to perform different logic when it occurs. Using or subclassing in this case from runtime_exception in most cases fails the "is a" test.

Should I inherit from std::exception?

I've seen at least one reliable source (a C++ class I took) recommend that application-specific exception classes in C++ should inherit from std::exception. I'm not clear on the benefits of this approach.
In C# the reasons for inheriting from ApplicationException are clear: you get a handful of useful methods, properties and constructors and just have to add or override what you need. With std::exception it seems that all you get is a what() method to override, which you could just as well create yourself.
So what are the benefits, if any, of using std::exception as a base class for my application-specific exception class? Are there any good reasons not to inherit from std::exception?
The main benefit is that code using your classes doesn't have to know exact type of what you throw at it, but can just catch the std::exception.
Edit: as Martin and others noted, you actually want to derive from one of the sub-classes of std::exception declared in <stdexcept> header.
The problem with std::exception is that there is no constructor (in the standard compliant versions) that accepts a message.
As a result I prefer to derive from std::runtime_error. This is derived from std::exception but its constructors allow you to pass a C-String or a std::string to the constructor that will be returned (as a char const*) when what() is called.
Reason for inheriting from std::exception is it "standard" base class for exceptions, so it is natural for other people on a team, for example, to expect that and catch base std::exception.
If you are looking for convenience, you can inherit from std::runtime_error that provides std::string constructor.
I once participated in the clean up of a large codebase where the previous authors had thrown ints, HRESULTS, std::string, char*, random classes... different stuff everywhere; just name a type and it was probably thrown somewhere. And no common base class at all. Believe me, things were much tidier once we got to the point that all the thrown types had a common base we could catch and know nothing was going to get past. So please do yourself (and those who'll have to maintain your code in future) a favor and do it that way from the start.
You should inherit from boost::exception. It provides a lot more features and well-understood ways to carry additional data... of course, if you're not using Boost, then ignore this suggestion.
Yes you should derive from std::exception.
Others have answered that std::exception has the problem that you can't pass a text message to it, however it is generally not a good idea to attempt to format a user message at the point of the throw. Instead, use the exception object to transport all relevant information to the catch site which can then format a user-friendly message.
The reason why you might want to inherit from std::exception is because it allows you to throw an exception that is caught according to that class, ie:
class myException : public std::exception { ... };
try {
...
throw myException();
}
catch (std::exception &theException) {
...
}
There is one problem with inheritance that you should know about is object slicing. When you write throw e; a throw-expression initializes a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw. That could be not what you're expecting. Example of problem you could find here.
It is not an argument against inheritance, it is just 'must know' info.
Difference: std::runtime_error vs std::exception()
Whether you should inherit from it or not is up to you. Standard std::exception and its standard descendants propose one possible exception hierarchy structure (division into logic_error subhierarchy and runtime_error subhierarchy) and one possible exception object interface. If you like it - use it. If for some reason you need something different - define your own exception framework.
Whether to derive from any standard exception type or not is the first question. Doing so enables a single exception handler for all standard library exceptions and your own, but it also encourages such catch-them-all handlers. The problem is that one should only catch exceptions one knows how to handle. In main(), for example, catching all std::exceptions is likely a good thing if the what() string will be logged as a last resort before exiting. Elsewhere, however, it's unlikely to be a good idea.
Once you've decided whether to derive from a standard exception type or not, then the question is which should be the base. If your application doesn't need i18n, you might think that formatting a message at the call site is every bit as good as saving information and generating the message at the call site. The problem is that the formatted message may not be needed. Better to use a lazy message generation scheme -- perhaps with preallocated memory. Then, if the message is needed, it will be generated on access (and, possibly, cached in the exception object). Thus, if the message is generated when thrown, then a std::exception derivate, like std::runtime_error is needed as the base class. If the message is generated lazily, then std::exception is the appropriate base.
Since the language already throws std::exception, you need to catch it anyway to provide decent error reporting. You may as well use that same catch for all unexpected exceptions of your own. Also, almost any library that throws exceptions would derive them from std::exception.
In other words, its either
catch (...) {cout << "Unknown exception"; }
or
catch (const std::exception &e) { cout << "unexpected exception " << e.what();}
And the second option is definitely better.
If all your possible exceptions derive from std::exception, your catch block can simply catch(std::exception & e) and be assured of capturing everything.
Once you've captured the exception, you can use that what method to get more information. C++ doesn't support duck-typing, so another class with a what method would require a different catch and different code to use it.
Though this question is rather old and has already been answered plenty, I just want to add a note on how to do proper exception handling in C++11, since I am continually missing this in discussions about exceptions:
Use std::nested_exception and std::throw_with_nested
It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.
Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!
You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
You don't even need to subclass std::runtime_error in order to get plenty of information when an exception is thrown.
The only benefit I see in subclassing (instead of just using std::runtime_error) is that your exception handler can catch your custom exception and do something special. For example:
try
{
// something that may throw
}
catch( const MyException & ex )
{
// do something specialized with the
// additional info inside MyException
}
catch( const std::exception & ex )
{
std::cerr << ex.what() << std::endl;
}
catch( ... )
{
std::cerr << "unknown exception!" << std::endl;
}
Another reason to sub-class exceptions is a better design aspect when working on large encapsulated systems. You can reuse it for things such as validation messages, user queries, fatal controller errors and so on. Rather than rewriting or rehooking all of your validation like messages you can simply "catch" it on the main source file, but throw the error anywhere in your entire set of classes.
e.g. A fatal exception will terminate the program, a validation error will only clear the stack and a user query will ask the end-user a question.
Doing it this way also means you can reuse the same classes but on different interfaces. e.g. A windows application can use message box, a web service will show html and reporting system will log it and so on.

Difference: std::runtime_error vs std::exception()

What is the difference between std::runtime_error and std::exception? What is the appropriate use for each? Why are they different in the first place?
std::exception is the class whose only purpose is to serve as the base class in the exception hierarchy. It has no other uses. In other words, conceptually it is an abstract class (even though it is not defined as abstract class in C++ meaning of the term).
std::runtime_error is a more specialized class, descending from std::exception, intended to be thrown in case of various runtime errors. It has a dual purpose. It can be thrown by itself, or it can serve as a base class to various even more specialized types of runtime error exceptions, such as std::range_error, std::overflow_error etc. You can define your own exception classes descending from std::runtime_error, as well as you can define your own exception classes descending from std::exception.
Just like std::runtime_error, standard library contains std::logic_error, also descending from std::exception.
The point of having this hierarchy is to give user the opportunity to use the full power of C++ exception handling mechanism. Since 'catch' clause can catch polymorphic exceptions, the user can write 'catch' clauses that can catch exception types from a specific subtree of the exception hierarchy. For example, catch (std::runtime_error& e) will catch all exceptions from std::runtime_error subtree, letting all others to pass through (and fly further up the call stack).
P.S. Designing a useful exception class hierarchy (that would let you catch only the exception types you are interested in at each point of your code) is a non-trivial task. What you see in standard C++ library is one possible approach, offered to you by the authors of the language. As you see, they decided to split all exception types into "runtime errors" and "logic errors" and let you proceed from there with your own exception types. There are, of course, alternative ways to structure that hierarchy, which might be more appropriate in your design.
Update: Portability Linux vs Windows
As Loki Astari and unixman83 noted in their answer and comments below, the constructor of the exception class does not take any arguments according to C++ standard. Microsoft C++ has a constructor taking arguments in the exception class, but this is not standard. The runtime_error class has a constructor taking arguments (char*) on both platforms, Windows and Linux. To be portable, better use runtime_error.
(And remember, just because a specification of your project says your code does not have to run on Linux, it does not mean it does never have to run on Linux.)
std::exception should be considered (note the considered) the abstract base of the standard exception hierarchy. This is because there is no mechanism to pass in a specific message (to do this you must derive and specialize what()). There is nothing to stop you from using std::exception and for simple applications it may be all you need.
std::runtime_error on the other hand has valid constructors that accept a string as a message. When what() is called a const char pointer is returned that points at a C string that has the same string as was passed into the constructor.
try
{
if (badThingHappened)
{
throw std::runtime_error("Something Bad happened here");
}
}
catch(std::exception const& e)
{
std::cout << "Exception: " << e.what() << "\n";
}