When should you create your own exception type?
Using the same exception everywhere is easy. Especially when trying to catch that exception. Unfortunately, it opens the door for Pokemon exception handling. It brings the risk of catching exceptions you don't expect.
Using a dedicated exception for all the different modules adds several advantages:
- A custom message for each case, making it more useful for reporting
- Catch can capture only the intended exceptions, more easily crashes on unexpected cases (yes, thats an advantage over incorrect handling)
- On crash, IDE can show the exception type, helping even more with debugging
Create your own exception types when:
- you might want to differentiate them when handling. If they're different types, you have the option to write different
catch
clauses. They should still have a common base so you can have common handling when that is appropriate - you want to add some specific structured data you can actually use in the handler
Having separate list
and vector
exceptions doesn't seem worthwhile, unless there's something distinctively list-like or vectorish about them. Are you really going to have different catch handling depending on which type of container had an error?
Conversely it could make sense to have separate exception types for things that might be recoverable at runtime, versus things that are rolled-back but could be retried, versus things that are definitely fatal or indicate a bug.