Junior
How would you throw exceptions higher up in the call stack?
sobes.tech AI
Answer from AI
I use the keyword throw to rethrow or create a new exception.
public void method1() throws CustomException {
try {
// Some code that might throw AnotherException
method2();
} catch (AnotherException e) {
// Catching AnotherException
// Wrapping it in a CustomException and throwing it up
throw new CustomException("Error in Method2: " + e.getMessage(), e);
}
}
public void method2() throws AnotherException {
// Some code that might throw an exception
throw new AnotherException("Something went wrong 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);
}
}
Alternatively, if you just want to rethrow the caught exception without creating a new one:
public void methodA() throws SomeException {
try {
methodB();
} catch (SomeException e) {
// Logging or other actions
// Rethrow the same exception up the stack
throw e;
}
}
public void methodB() throws SomeException {
// Code that might throw SomeException
throw new SomeException("Error in MethodB");
}
class SomeException extends Exception {
public SomeException(String message) {
super(message);
}
}