In which situations do you use them?
Try... catch - for exceptional conditions, i.e. conditions which aren't caused by malformed code, but which may just alter the normal control flow by external unpredictable events.
Assertions for catching invalid code, i.e. checking if an invariant is held in the function, checking if an internal method is called with right arguments (for public API you might still want an exception for that), etc.
Those are my basic guidelines, but the conventions vary from situation to situation and from language to language.
When you're in doubt, you can ask yourself: is that specific safety check supposed to still be there in the release code, after we test and finish everything? If you answer "yes, it's still neccessary then", you probably want an exception. Otherwise, you probably want an assertion.
Normally assert()
does not work in release code, so it can never replace a try-catch
strategy. Nevertheless I like to use assert()
in places where exceptions are thrown. For me (as a developer!), it is often more convenient to get by an assert()
message to the line of failure than through the exception stack.
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