Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine if exception is rethrowable

I have 2 functions:

public void WithdrawMoney()
{
    //Take money from bank account
    //Exceptions abort the operation and are printed
    //Rethrow exception if called by TransferMoney()
}

public void TransferMoney()
{
    //Take money from one account and only deposit on another account if no exceptions were caught in WithdrawMoney()
    WithdrawMoney(); 
    DepositMoney();     
}

What I want is to be able to rethrow an exception that occured in WithdrawMoney(), only if it was called by TransferMoney(). If I just want to withdraw money from an account, the exception must be handled, but does not have to be rethrown as it was not called by another method.

Besides working with bools, there is another solution that comes to my mind. I could look into the stacktrace, see if TransferMoney() called WithdrawMoney() and only rethrow the exception if it did. Or is there a way to see if an exception occured in a method?

I just want to know if you can check whether an exception is throwable in a catch block before throwing it. If I always throw it, the exception will be unhandled when I just call WithdrawMoney() directly.

like image 257
Glenn Avatar asked Dec 27 '22 18:12

Glenn


1 Answers

A method shouldn't behave differently because of some arbitrary condition that is hard to follow and document.

You should refactor out the part of the withdrawal method that you want to use internally, so that you get one method to use from the outside and one from the inside.

private void MakeWithdrawal() {
    //Take money from bank account
    //Exceptions abort the operation
}

public void WithdrawMoney()
{
    MakeWithdrawal();
    //Exceptions are printed
}

public void TransferMoney()
{
    //Take money from one account and only deposit on another account if no exceptions were caught in WithdrawMoney()
    MakeWithdrawal();
    DepositMoney();     
    //Exceptions are printed
}
like image 186
Guffa Avatar answered Dec 29 '22 09:12

Guffa