Exceptions in Java: try, catch, finally and throw
Handle runtime errors without crashing the program. With a simulator where you trigger and catch exceptions.
Una excepción es un error que ocurre mientras el programa se ejecuta (dividir entre
cero, un índice fuera de rango, un null…). Sin control, el programa peta. Con
try/catch lo interceptas y decides qué hacer.
try {
int r = 10 / divisor; // puede fallar
System.out.println(r);
} catch (ArithmeticException e) {
System.out.println("No se puede dividir entre cero");
} finally {
System.out.println("Esto se ejecuta siempre");
}
Exception simulator
Elige una operación peligrosa y mira qué excepción lanza, cómo se captura y el orden de ejecución.
Checked vs unchecked
Las unchecked (heredan de RuntimeException: NullPointerException,
ArithmeticException…) no obligan a nada. Las checked (IOException,
SQLException…) el compilador te obliga a capturarlas o declararlas con throws.
| Checked | Unchecked | |
|---|---|---|
| Hereda de | Exception | RuntimeException |
| ¿El compilador obliga a tratarla? | Sí | No |
| Ejemplos | IOException, SQLException, FileNotFoundException | NullPointer, ArrayIndexOutOfBounds, NumberFormat, Arithmetic |
| Suelen indicar | Fallo externo (fichero, red, BD) | Bug del programador |
Throwing your own exceptions
class SaldoInsuficienteException extends RuntimeException {
SaldoInsuficienteException(String msg) { super(msg); }
}
void retirar(double cantidad) {
if (cantidad > saldo)
throw new SaldoInsuficienteException("Faltan " + (cantidad - saldo) + " €");
saldo -= cantidad;
}
finally and try-with-resources
finally se ejecuta pase lo que pase (haya error o no): ideal para cerrar recursos. Aún
mejor: try (Scanner sc = new Scanner(...)) cierra sc automáticamente al salir.
Check what you've learned
finally?Integer.parseInt("hola") lanza…