Checked exceptions are a powerful tool in Java, as they force the programmer to handle exceptional conditions, increasing code reliability. However, excessive use can make APIs difficult to use. For a checked exception to be justified, the situation must be truly exceptional and capable of useful action on the part of the programmer. Otherwise, an unchecked exception might be more appropriate.
Java 8 brought an additional challenge to the use of checked exceptions, since methods that throw them cannot be used directly in streams, requiring additional handling in the code. To avoid this complexity, alternatives can be considered, such as returning an Optional object instead of throwing a verifiable exception, or splitting the method into two, one that checks for the possibility of an error and another that performs the operation.
Checked exceptions should be used sparingly: if recovery is not possible, use unchecked exceptions. When recovery is feasible, consider Optional for return. If this does not provide enough information, then a checked exception may be justified.
Plus:
Here are some examples to illustrate the proper use of checked exceptions and alternatives such as Optional and the use of check methods.
Using Checked Exceptions Sparingly
Let's say we have a method that loads data from a file. If the file is not found, we want to throw an exception to notify the caller of the problem. In this case, a checked exception is appropriate because the developer can take action to resolve the issue (such as providing the correct archive path).
public class FileLoader { public String loadFile(String filePath) throws FileNotFoundException { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException("Arquivo não encontrado: " + filePath); } // Código para carregar o arquivo return "Conteúdo do arquivo"; } }
Here the caller needs to handle the FileNotFoundException exception as he can fix the problem by providing a correct path to the file.
Using Optional instead of Checked Exceptions
If the missing file is a condition that should not interrupt normal execution, we can use Optional to indicate that the result can be missing without throwing an exception. This makes the API more fluid for cases where a lack of value can be tolerated.
import java.util.Optional; public class FileLoader { public Optional<String> loadFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return Optional.empty(); } // Código para carregar o arquivo return Optional.of("Conteúdo do arquivo"); } }
In caller code:
FileLoader loader = new FileLoader(); Optional<String> content = loader.loadFile("caminho/para/arquivo.txt"); content.ifPresentOrElse( System.out::println, () -> System.out.println("Arquivo não encontrado.") );
In this example, the caller does not need to handle exceptions, and Optional allows it to more smoothly handle missing content.
Dividing the Method into Two: Verification and Action
In some cases, we can divide the method into two: one that checks the condition and another that performs the action. This allows the caller to handle the exceptional condition before calling the main method, making the API more flexible.
public class FileLoader { public String loadFile(String filePath) throws FileNotFoundException { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException("Arquivo não encontrado: " + filePath); } // Código para carregar o arquivo return "Conteúdo do arquivo"; } }
In caller code:
import java.util.Optional; public class FileLoader { public Optional<String> loadFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return Optional.empty(); } // Código para carregar o arquivo return Optional.of("Conteúdo do arquivo"); } }
Here we use IllegalStateException, an unchecked exception, in the case where the caller tries to load the file without first checking if it is available.
Summary
Checked Exception: Use for conditions that the caller can fix directly, such as FileNotFoundException for files.
Optional: Use when the absence of a value should not interrupt the program flow.
Method Division: Separate checking and execution methods when the error can be predicted and avoided, making the API more flexible and simple to use.
The above is the detailed content of Item Avoid unnecessary use of checked exceptions. For more information, please follow other related articles on the PHP Chinese website!