Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you judge whether to make an exception checked or unchecked?

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?

like image 966
temporary_user_name Avatar asked Mar 04 '21 05:03

temporary_user_name


People also ask

How can you tell if an exception is checked or unchecked?

Difference Between Checked and Unchecked Exceptions in JavaA checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.

When would use an unchecked exception?

Unchecked exceptions result from faulty logic that can occur anywhere in a software program. For example, if a developer invokes a method on a null object, an unchecked NullPointerException occurs.

Why do we have checked and unchecked exceptions?

Remember the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by the compiler and used to indicate exceptional conditions that are out of the control of the program, while unchecked exceptions are occurred during runtime and are used to indicate programming errors.

What are checked and unchecked exceptions examples?

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.


1 Answers

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.

like image 66
EricSchaefer Avatar answered Oct 12 '22 20:10

EricSchaefer