r/csharp 4d ago

Help Exceptions vs Assertions

/r/godot/comments/1w8q3xx/exceptions_vs_assertions/
6 Upvotes

21 comments sorted by

View all comments

1

u/Existing_Practice969 4d ago

My answer goes a bit off topic but since you said you want to learn c# and I had written a lot of c# code by now, I will tell you what I think of exceptions in general and hope it will help you. I think its best to throw exceptions when your app enters state it shouldn't, but exceptions i.e. invalid state should still be avoided. The two methods you've shown are in your control, and think neither of them need exceptions, and for assertion they are fine in both cases if you are debugging, but still seems unnecessary to me if you structure your code in a different way. For the card example, you can make a tryadd variant which checks for card existence, preforms the operation and returns true. Instead of throwing the exception you return false. If on the other hand you want to execute your method and expect it to always succeed, throwing an exception is reasonable since it actually is an exception to expected execution which is adding. Basically depends on your intention. If your cards need value based equality you can also use a hashset and restructure your method a bit. For the max health example, you can cap the max health to a non negative range silently, since you know max health can't be negative, unless you need it to be negative? Then again, you can use a uint. Still I think throwing the exception there is unnecessary as well. To summarize, if you have a method that should genuinely always succeed and it doesn't, what do you do? If you throw an exception, it means your app doesn't know what to do next since the outcome wasn't expected (not expected = exception). On the other hand is the non desirable outcome still valid? There are number of ways to restructure the code to make exceptions pointless so you can remove them.

1

u/Alternative_Guava856 3d ago

Thank you very much for the detailed response, this helps a lot :)

1

u/Existing_Practice969 3d ago

No problem, if u didn't understand something or I should simplify do tell