if/else statements or exceptions

Posted by Thaven on Programmers See other posts from Programmers or by Thaven
Published on 2012-03-26T12:26:01Z Indexed on 2012/03/26 17:38 UTC
Read the original article Hit count: 341

I don't know, that this question fit better on this board, or stackoverflow, but because my question is connected rather to practices, that some specified problem. So, consider an object that does something. And this something can (but should not!) can go wrong. So, this situation can be resolved in two way:

first, with exceptions:

DoSomethingClass exampleObject = new DoSomethingClass();
try
{
     exampleObject.DoSomething();
}
catch (ThisCanGoWrongException ex)
{
     [...]
}

And second, with if statement:

DoSomethingClass exampleObject = new DoSomethingClass();
if(!exampleObject.DoSomething())
{
     [...]
}

Second case in more sophisticated way:

DoSomethingClass exampleObject = new DoSomethingClass();
ErrorHandler error = exampleObject.DoSomething();
if (error.HasError)
{
     if(error.ErrorType == ErrorType.DivideByPotato)
     {
         [...]
     }
}

which way is better? In one hand, I heard that exception should be used only for real unexpected situations, and if programist know, that something may happen, he should used if/else. In second hand, Robert C. Martin in his book Clean Code Wrote, that exception are far more object oriented, and more simple to keep clean.

© Programmers or respective owner

Related posts about programming-practices

Related posts about exceptions