Junior
Hoe zou je uitzonderingen hoger in de call stack gooien?
sobes.tech AI
Antwoord van AI
Ik gebruik het sleutelwoord throw om een uitzondering opnieuw te werpen of een nieuwe te maken.
public void method1() throws CustomException {
try {
// Sommige code die AnotherException kan gooien
method2();
} catch (AnotherException e) {
// Vangen van AnotherException
// Wikkel het in CustomException en werp het omhoog
throw new CustomException("Fout in Method2: " + e.getMessage(), e);
}
}
public void method2() throws AnotherException {
// Sommige code die een uitzondering kan gooien
throw new AnotherException("Er is iets misgegaan 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);
}
}
Of, als je gewoon de gevangen uitzondering wilt doorgeven zonder een nieuwe te maken:
public void methodA() throws SomeException {
try {
methodB();
} catch (SomeException e) {
// Logging of andere acties
// Geef dezelfde uitzondering door naar boven
throw e;
}
}
public void methodB() throws SomeException {
// Code die SomeException kan gooien
throw new SomeException("Fout in MethodB");
}
class SomeException extends Exception {
public SomeException(String message) {
super(message);
}
}