7

I was reading about checked vs unchecked exceptions in Java and when to use each:

Here's the bottom line: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

An example of something a client can't be expected to recover from is divide by zero, where something they can recover from is a FileNotFound exception. I don't see the difference yet though. Why can you catch one and log an error but not catch the other and log the error? What makes something reasonably recoverable? Can't you catch an error (thus recovering) in all circumstances?

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • This may be opinion-based, just as the whole checked/unchecked exception design is. And my opinion is that this distinction itself is one big thing too many for Java developers to worry about. Coding wouldn't be worse without checked exceptions in Java... on the contrary... – ernest_k Mar 04 '21 at 05:43
  • The original idea was that checked exceptions are for failure modes that the caller is expected to have some idea how to handle (e.g., network failed; retry) and that unchecked exceptions indicate actual software bugs (failure to validate input). – chrylis -cautiouslyoptimistic- Mar 04 '21 at 06:27
  • This is a good question, but it is a design question/philosophical issue. .NET, for example, decided not to use checked exceptions -- because in most cases you need to generally catch Exceptions in a meaningful spot so that the app can keep running. See [Why are Exceptions not Checked in .NET](https://stackoverflow.com/questions/124143/why-are-exceptions-not-checked-in-net). – Sam Goldberg Mar 04 '21 at 16:31

2 Answers2

2

The meaning of the quote is this: If the client code can not recover from the problem, it needs to let the exception propagate to higher layers. If you use checked exceptions for that, you need to declare the checked exception through all call layers without benefit.

To rephrase the quote: If the exception is expected to propagate through the layers, make it unchecked. Only make it checked if the caller can actually do something about it.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
0

When an exception is checked and the exception occurs, its easy to troubleshoot the reason for exception. If we don't use checked exceptions, it would be very difficult to figure out the reason of exception. Checked exception gives an idea of the expected exception.

O_K
  • 922
  • 9
  • 14