C# Exceptions – Best Practices for Using Exceptions in Libraries

cexceptions

I'm writing a library which will be a base for a turn-based battle system but i don't know what are the best practices for exception handling, has anybody some advice for me?

Should I catch every generic exceptions/ exceptions thrown by standard components (like lists,dictionaries,etc…) and then throw a contextualized exception?

If I have public method that throws an exception, when I call it from another library method should i catch the exception and then re-throw it? And if the method is private?

EDIT: I'm sorry I didn't mention that I throw exceptions only when there are some bugs

Best Answer

First, this will be an opinion, so many reasonable answers will be downvoted by those who have different opinions. Second, it will be somewhat language and platform dependent: an approach that should be slightly better but is incredibly clunky in the language is a bad approach.

The most important choice is to have an understandable plan and communicate it. You probably are thinking of these types of errors:

  • You called the library incorrectly and want to give you the correct error message. You might choose to "output the error message and crash" as this is a development time bug.
  • A dependency passed an error or responded incorrectly. For example, the GUI refuses to allocate colors. As you cannot handle it, just bubbling it upwards is fine.
  • An unusual return value occurred. It's an exceptional value, e.g., "creature cannot find route to target" or "route is too long" but still a known and valid return. Many languages work better if this bubbles up as an exception. The user of the library may choose what makes sense for the game.

I recommend you pick and document a naming scheme for problems so that a developer knows what type of exception is passed upwards.

Related Topic