When validating data, I've gotten into a habit of doing the following:
Note: I don't really have individual booleans for each check. This is just for the example.
Another Note: any error handling during the tests are done properly. The ONLY exceptions thrown in the try-catch are my own.
try { if (validCheckOne = false) { throw new Exception("Check one is bad"); } if (validCheckTwo = false) { throw new Exception("Failed because of check2"); } if(validCheckTen = false) { throw new Exception("Yet another failure on your part: check10."); } } catch(Exception e) { MessageBox.Show("Your stupid data is wrong! See for yourself: " + e.Message); }
Is this bad practice? Does throwing Exceptions slow the program's execution or is inadvisable?
Personally I like throwing Exceptions for business rule validation (not so much for user input validation) because it forces the problem to be handled upstream. If my business objects returned some kind of validation result, it could be ignored by the caller. Call me a cowboy if you wish :)
Everyone here is repeating the phrase "exceptions are for exceptional circumstances", but that really doesn't give any understanding of why its bad to use them for unexceptional circumstances. I need more than that. Is the performance hit of throwing exceptions really that bad? Are there any benchmarks available?
I'm going to repeat the mantra here: throwing exceptions should be done in exceptional circumstances. Invalid entered data is really not that exceptional.
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