Lots of interviewers asked me about my exception handling strategy. Here’s a tentative exception object design for a small project — Maintain just 2 custom exception classes.
1) MyCheckedEx.java — a big custom checked exception (by extending Exception.java?) containing an enum[2] field. Each value represents a specific error condition[1].
2) MyUncheckedEx — a similar thing but unchecked (extending RuntimeException?).
Now the usage:
1) When you want a given error situation to always be handled in every *context* and never ignored, then register it in MyCheckedEx. Every place it can possibly occur, compiler will be your trusted friend to ensure it’s declared and handled explicitly.
2) things you put into MyUncheckedEx are nicely flexible, less strict. Callers (other developers) can choose to catch them or ignore them, silently escalating them to upstairs.
What about standard JVM exceptions? You can wrap them into your 2 exceptions. In particular, if you don’t like to handle many of the standard checked exceptions, you can wrap them in MyUncheckedEx. I think Spring wraps lots of Checked exceptions into unchecked. Conversely, you can wrap an unchecked exception into MyCheckedEx.
Another requirement — We often need a hierarchy of exceptions. Gmail uses labels instead of folders, so likewise, shall we declare some marker interfaces so an exception can be labeled as both validation and synchronization and billing exceptions? Will this beat a custom inheritance tree?
[1] a priority — i prefer fine-grained types of exception, for better control
[2] or int. You can use these in switch-case. I don’t like String.
non-priority — exception parent-child family. Unnecessary complexity.