Timeline for When to use assertions and when to use exceptions?
Current License: CC BY-SA 2.5
7 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Apr 20, 2022 at 8:43 | comment | added | Géry Ogam | External input does not mean external to your code, it means external to code (e.g. file system, network, environment variables, signals, out of memory). Arguments passed to your functions are internal to code (e.g. your library/framework code + another developer’s application code using it). It is the responsibility of the caller of your functions to check arguments and raise exceptions if they violate your function’s precondition, not the responsibility of your functions. If you don’t trust the caller, you are not doing design by contract but defensive programming (the exact opposite). | |
| Mar 16, 2021 at 23:00 | comment | added | simplename | Then why do I as a user trigger asserts in libraries such as opencv for example through public functions? | |
| Mar 9, 2012 at 13:11 | comment | added | Bill Michell | In java, at least, you have to typically enable the assertion check with the -ea command line parameter. This means assertions are effectively no-ops, unless you explicitly turn them on. | |
| Jan 14, 2011 at 13:50 | vote | accept | gablin | ||
| Oct 29, 2010 at 10:40 | comment | added | Frank Shearar | And inevitably you'll find those assertions being triggered in production. +1 for verifying private stuff with asserts! Maybe you could say "use asserts when you are in full control of the inputs"? | |
| Oct 29, 2010 at 10:12 | comment | added | ChrisF | Good point about using exceptions for external inputs. I'd also add outputs to that too - problems when trying to create/write to file/database etc. | |
| Oct 29, 2010 at 9:18 | history | answered | Note to self - think of a name | CC BY-SA 2.5 |