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

后端 未结 14 920
你的背包
你的背包 2020-12-07 16:27

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

14条回答
  •  失恋的感觉
    2020-12-07 17:08

    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.

提交回复
热议问题