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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With