As a team lead which type of exception should I create a base class for in my architecture - checked or unchecked ? My team would start development in a few weeks and I want the architecture to be conducive to them for usage. Any reasons around that would also help.
That depends on the situation.
You use checked exceptions (extend Exception
) for things that can go wrong regardless of the input the caller of the method passes. For example, network connections; you can make an HTTP GET
request by calling client.get("google.com");
and everything goes well, two minutes later you call once again client.get("google.com");
and then you get an exception because of a network error. As you can see, here you called the same method passing the exact same input "google.com"
, yet you can get an exception at anytime. Therefore, you must force the caller to catch the exception by making it "checked", so that they handle those cases in which a network error occurs.
You use unchecked exceptions (extend RuntimeException
) when the error happens because of some sort of invalid input by the caller of the method. For example, you have the method Integer.parse(String);
. The method cannot work properly if you pass a null
string here, so you throw an exception if that happens. This case, you should not force the caller to catch it, because the caller is responsible of passing the right input.