Sobes.tech
Junior

Cum ai arunca excepții mai sus în stiva de apeluri?

sobes.tech AI

Răspuns de la AI

Utilizez cuvântul cheie throw pentru a relua sau a crea o excepție nouă.

public void method1() throws CustomException {
    try {
        // Cod care poate arunca AnotherException
        method2();
    } catch (AnotherException e) {
        // Prindem AnotherException
        // Îl înfășurăm în CustomException și îl aruncăm mai sus
        throw new CustomException("Eroare în Method2: " + e.getMessage(), e);
    }
}

public void method2() throws AnotherException {
    // Cod care poate arunca o excepție
    throw new AnotherException("Ceva nu a mers bine în Method2");
}

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

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

Sau, dacă vrei doar să reluți excepția prinsă, fără a crea una nouă:

public void methodA() throws SomeException {
    try {
        methodB();
    } catch (SomeException e) {
        // Înregistrare sau alte acțiuni
        // Reluăm aceeași excepție mai sus în stivă
        throw e;
    }
}

public void methodB() throws SomeException {
    // Cod care poate arunca SomeException
    throw new SomeException("Eroare în MethodB");
}

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