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.
Why exceptions?
Why wont you just let (possibly even both) methods return bool, indicating success?
It sounds like you had the bools idea, but didn’t go for it for some reason. Why the heck not? It’s so logical and simple!
Withdraw money handles inner exceptions and returns false, which the TransferMoney will check and return false as well. It is also very logical that you will want those operations to return whether the operation was successful.
After all that – I would say that you also need to check the 2nd WithdrawMoney operation did not fail, and in case it did – rollback the changes you’ve done with the 1st WithdrawMoney.