Types of exceptions in Java:
Checked Exceptions: for recoverable conditions that the caller can recover from.
Runtime Exceptions: for programming errors, such as violating preconditions (for example, accessing an invalid index of an array).
Bugs: Generally reserved for the JVM and should not be used by developers.
Checked Exceptions vs. Runtime Exceptions:
Use checked exceptions if the calling code can take action to resolve the situation.
Use runtime exceptions to indicate flaws in the API contract, which must be fixed by the developer.
// Exemplo de exceção verificada (condição recuperável) public void readFile(String filePath) throws IOException { // código para leitura do arquivo } // Exemplo de exceção de runtime (erro de programação) public int getElement(int[] array, int index) { if (index < 0 || index >= array.length) { throw new ArrayIndexOutOfBoundsException("Index out of bounds"); } return array[index]; }
Provide helper methods on checked exceptions:
Checked exceptions must include methods to help the caller deal with the exceptional condition.
Example: If a purchase fails due to insufficient balance, provide the deficit amount so the caller can view this information.
public class InsufficientFundsException extends Exception { private final double deficit; public InsufficientFundsException(double deficit) { super("Saldo insuficiente: falta " + deficit); this.deficit = deficit; } public double getDeficit() { return deficit; } }
Summary
Use exceptions for exceptional situations and not as an alternative control flow.
Differentiate between checked and runtime exceptions to indicate to the caller the type of handling required.
Include helper methods in checked exceptions to provide useful information to the caller, facilitating recovery.
These principles help keep code clearer, more efficient, and easier to debug.
The above is the detailed content of Item Use checked exceptions for recoverable conditions and runtime exceptions for programming errors. For more information, please follow other related articles on the PHP Chinese website!