Imagine the following code as a part of some program (java):
function z(){
try{
//some code here, that might throw exceptions.
}catch (SomeException | SomeOtherException e){
//some exception handling here.
}
function y(){
z();
}
function x(){
y();
}
And imagine that functions x and y won't execute as intended if Exceptions SomeException or SomeOtherException are thrown within function z. We want to write our code such that functions x and y know that Exceptions were thrown in function z, and make them act accordingly. Whats the best way to do this?
function z() thrown FunctionZFailedException{
try{
//some code here, that might throw exceptions.
}catch (SomeException | SomeOtherException e){
throw new FunctionZFailedException();
}
}
function y() throws FunctionYFailedException{
try{
z();
}catch (FunctionZFailedException e){
throw new FunctionYFailedException();
}
}
function x(){
try{
y();
}catch (FunctionYFailedException e){
//Do something, like alerting user that something went wrong.
}
}
Is this too excessive, that is declaring new exceptions with the sole purpose of "forwarding" other exceptions up to a higher level?
I think we could also just let SomeException and SomeOtherException fly up and catch them inside function x. But imo that might make up for less readable code,
for example if the exceptions caught in function z are SQLException and NoSuchAlgorithmException, and function y is a login() function. Then function x would try to call login(), and either catch a SQLException | NoSuchAlgorithmException, if the let those exceptions simply fly up to the highest level, or catch a LoginFailedException, if we catch each exceptions immediately, and have them throw new exceptions. It seems like catching a LoginFailedException makes for more readable code.
Imo both ways have their cons (less readable code vs introducing many exceptions) and I'm wondering how similar cases are usually handled by seasoned java programmers.
Any general thoughts on exceptions also appreciated thanks guys