When to use Exceptions?

Started by
2 comments, last by Thomas M 16 years, 10 months ago
Hello, I'm wondering when I should use exceptions. Right now I have something like this:


...
try
{
  GameApp game(inst); 
  game.Run();
}
catch(core::Exception& e)
{ 
  e.DisplayMessageBox();
  e.WriteToLogFile();
}
...

If for example during my graphics initialization something fails (can't create D3DDevice, etc.) I throw an exception and the user gets a message box with nice error description. For stuff like this is it better to use Logging via I/O, or if-statements with MessageBox (like in NeHe tutorials for example). Or is it just a matter of taste? Greetings, Thomas
Advertisement
At base, exceptions are chiefly important not for reporting problems, but for recovering from problems. If all you want to do is display a message and crash the game, you don't need exceptions. As such, the question of what you do when you encounter a truly unrecoverable exception is a matter of taste. You should spend your time thinking about what to do when you encounter an exception which is not unrecoverable, and how to place your try/catch blocks such that exceptions become recoverable. (Hint: wrapping your entire game loop in one is a useless idea.)
Throwing an exception is a good candidate for the error reporting mechanism when the code that is directly calling yours doesn't have the context needed to handle the error (but code further "upstream" might).

In C, when an "inner" function fails, you typically have to pass the returned error code out of a bunch of functions to the point in the code where you can handle it properly.

It's arguably tedious and error-prone to check for failure on every function and propagate the error up manually.

Exceptions in C++ alleviate this problem somewhat, but they come with their own problems. The biggest is that you have to learn to write exception-safe code if you actually want to recover from them while maintaining all your system's invariants.

You also have to be careful when throwing exceptions over dynamic-library boundaries and out of child threads (the quirks are compiler/platform specific).

Writing code in an exception safe manner usually improves its structure, though, in my experience; you'll often find that you get commit-or-rollback semantics as a result.

Edd
Ok, thx a lot. I guess I'll be using logfiles/msg boxes/asserts for my problem checking.

When I come upon a specific situation which needs problem recovering (really can't think of any atm) I might consider using exceptions, though this article about writing exception-safe code scared me a lot. (I also have several DLLs, so this might also be a problem as you mentioned before.) :)

This topic is closed to new replies.

Advertisement