Sobes.tech
Junior

Como é que lançaria exceções mais acima na pilha de chamadas?

sobes.tech IA

Resposta da IA

Utilizo a palavra-chave throw para relançar ou criar uma nova exceção.

public void method1() throws CustomException {
    try {
        // Algum código que pode lançar AnotherException
        method2();
    } catch (AnotherException e) {
        // Capturamos AnotherException
        // Envolvê-lo em CustomException e lançá-lo para cima
        throw new CustomException("Erro no Method2: " + e.getMessage(), e);
    }
}

public void method2() throws AnotherException {
    // Algum código que pode lançar uma exceção
    throw new AnotherException("Algo deu errado no Method2");
}

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

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

Ou, se desejar apenas relançar a exceção capturada sem criar uma nova:

public void methodA() throws SomeException {
    try {
        methodB();
    } catch (SomeException e) {
        // Registro ou outras ações
        // Relançar a mesma exceção para cima
        throw e;
    }
}

public void methodB() throws SomeException {
    // Código que pode lançar SomeException
    throw new SomeException("Erro no MethodB");
}

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