AnyCompiler

Exception Handling

Un try block ejecuta código que podría lanzar una exception; un catch block correspondiente la maneja si eso ocurre. ArithmeticException aquí es una unchecked exception — el compilador no te obliga a manejarla, aunque es buena práctica hacerlo.

public class Main {
    static int divide(int a, int b) {
        return a / b;
    }

    public static void main(String[] args) {
        try {
            System.out.println(divide(10, 2));
            System.out.println(divide(10, 0));
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Output
5
Error: / by zero

Checked exceptions: cómo se ve un error real de compilación

Java tiene una segunda categoría sin equivalente en los otros lenguajes de este sitio: checked exceptions. Un method que puede lanzar una, como IOException aquí, tiene que capturarla o declarar throws IOException en su propia firma — si no hace ninguna de las dos, el código simplemente no compila. Esto es genuinamente lo que reporta javac — capturado de una ejecución real, no escrito para parecer plausible:

import java.io.IOException;

public class Main {
    static void risky() throws IOException {
        throw new IOException("something went wrong");
    }

    public static void main(String[] args) {
        risky();
    }
}
Output
Main.java:9: error: unreported exception IOException; must be caught or declared to be thrown
        risky();
             ^
1 error

risky() declara throws IOException, que es la parte del trato que le corresponde al method — pero main() llama a risky() sin capturar esa exception ni declarar su propio throws, así que el compilador se niega a compilar. Agregar try/catch alrededor de la llamada, o throws IOException a la propia firma de main, lo arreglaría de cualquiera de las dos formas.

Siguiente: generics — escribir una class o method que funcione con muchos types, con el compilador aún verificando la seguridad de tipos.

Practice exercise

Escribe un method safeDivide(int a, int b) que devuelva a / b, pero capture ArithmeticException y devuelva 0 si b es 0. Llámalo con (10, 0) e imprime el resultado.