if/else statements or exceptions
- by Thaven
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.