Sobes.tech
Junior

Come lanceresti eccezioni più in alto nello stack di chiamate?

sobes.tech AI

Risposta dell'AI

Utilizzo la parola chiave throw per rilanciare o creare una nuova eccezione.

public void method1() throws CustomException {
    try {
        // Qualche codice che può lanciare AnotherException
        method2();
    } catch (AnotherException e) {
        // Catturiamo AnotherException
        // Lo avvolgiamo in CustomException e lo rilanciamo
        throw new CustomException("Errore in Method2: " + e.getMessage(), e);
    }
}

public void method2() throws AnotherException {
    // Qualche codice che può lanciare un'eccezione
    throw new AnotherException("Qualcosa è andato storto in Method2");
}

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

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

Oppure, se vuoi semplicemente rilanciare l'eccezione catturata senza crearne una nuova:

public void methodA() throws SomeException {
    try {
        methodB();
    } catch (SomeException e) {
        // Log o altre azioni
        // Rilancia la stessa eccezione verso l'alto
        throw e;
    }
}

public void methodB() throws SomeException {
    // Codice che può lanciare SomeException
    throw new SomeException("Errore in MethodB");
}

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