Alex Rivera | Logout

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

Asked 2009-10-01T14:29:52.233
88

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?

Edit
Report

4 Answers

34

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

answered 2009-10-01T14:31:46.370
18

In addition to the oft-repeated statement that "exceptions are for exceptional circumstances", here's an additionally clarifying rule I've come to like:

If the user caused it, it's not exceptional.

Exceptions are for system-side things (servers going down, resources being unavailable), not for the user doing odd things, because all users do odd things.

answered 2009-10-01T14:39:08.337
1

In general it is inadvisable to use Exceptions to implement conditional flow. It would be better to do something like this

  error = false;
  while(true) {
    if(validCheckOne == false) { 
       msg = "Check one is bad"; 
       error = true;
       break;
    }

    if(validCheckTwo == false) { 
       msg = "Check two is bad"; 
       error = true;
       break;
    }
    ...
    break;
  }
  if (error) {
     ..
  }

You should throw an exception when there is a situation you can't do nothing about it. Higher layers of software would have a chance to catch the exception and do something about it - even if that is simply crashing the application.

answered 2009-10-01T14:35:56.627
0

It really only matters if your data validation is in a tight loop. For most cases, it doesn't matter what you choose as long as you are consistent in your code.

If you have a lot of code that looks like your sample above then you might want to clean it up by introducing a helper method to throw...

private void throwIf( bool condition, String message )
{
    if( condition )
        throw new ApplicationException( message );
}

(also, doing this will help zero in on errors such as "validCheckOne = false" versus "validCheckOne == false" :)

answered 2009-10-01T14:37:20.147

Your Answer