Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good or bad idea throwing Exceptions when validating data?

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?

like image 699
MoSlo Avatar asked Oct 01 '09 14:10

MoSlo


2 Answers

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?

like image 136
JonoW Avatar answered Sep 21 '22 20:09

JonoW


I'm going to repeat the mantra here: throwing exceptions should be done in exceptional circumstances. Invalid entered data is really not that exceptional.

like image 37
MusiGenesis Avatar answered Sep 20 '22 20:09

MusiGenesis