Sobes.tech
Junior

¿Cómo lanzaría excepciones más arriba en la pila de llamadas?

sobes.tech AI

Respuesta de la IA

Utilizo la palabra clave throw para volver a lanzar o crear una nueva excepción.

public void method1() throws CustomException {
    try {
        // Algún código que puede lanzar AnotherException
        method2();
    } catch (AnotherException e) {
        // Capturamos AnotherException
        // Lo envolvemos en CustomException y lo lanzamos hacia arriba
        throw new CustomException("Error en Method2: " + e.getMessage(), e);
    }
}

public void method2() throws AnotherException {
    // Algún código que puede lanzar una excepción
    throw new AnotherException("Algo salió mal en Method2");
}

class CustomException extends Exception {
    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
}

class AnotherException extends Exception {
    public AnotherException(String message) {
        super(message);
    }
}

O, si solo necesitas re-lanzar la excepción capturada sin crear una nueva:

public void methodA() throws SomeException {
    try {
        methodB();
    } catch (SomeException e) {
        // Registro o otras acciones
        // Re-lanzamos la misma excepción hacia arriba en la pila
        throw e;
    }
}

public void methodB() throws SomeException {
    // Código que puede lanzar SomeException
    throw new SomeException("Error en MethodB");
}

class SomeException extends Exception {
    public SomeException(String message) {
        super(message);
    }
}