I was reading on SO and SESE about exceptions and control flow, but I can't seem to determine or figure out if using exceptions to validate parameters is a violation of that guideline.
Suppose I had a method that wrote a message, obviously, I don't want the recipient of the message to be blank. For this example, recipient is a string
, but in a more sophisticated program, it might be a class with more parameters.
public void writeMessageto(string recipient, string message){
// check if recipient and message are blank and throw an
// exception if true.
... code to format and write message below....
}
In this particular instance is using exceptions controlling the flow of the program? I don't want to move on to sending a message if both parameters are blank.
Suppose if I had a Message
class, in the constructor, to build a valid object I would need to check it's parameters to make sure it isn't blank. If one of the parameters is null
or empty throw an exception and the object isn't created. Why is it okay in the Message
constructor
but not in the method?
If using if
statements are better, what happens when validation leads to deeply nested if
statements, but throwing an exception would make it more readable?