Should you favour if statements over exceptions?

Posts 1–5 of 5 · Page 1 of 1
Should you favour if statements over exceptions?
Say you have a class
Code:
Player
{
  private int turbosLeft;
  private car myCar;
  public void ActivateTurbo()
  {

  }
}
And there's a car that has a turboable variable

Code:
Car
{
  public bool turboAble = false;
}
Should you generate an exception for each seperate occasion? Ex.

Code:
 public void ActivateTurbo()
 {
   try{myCar.activateTurbo} 
   catch(NotTurboableException) { }
   catch(OutOfTurbosException) { }
 }
Or should you favour if-statements? Ex.

Code:
public void ActivateTurbo()
 { 
   if(!myCar.turboAble) { }
   else if(this.turbosLeft <= =) {}
 }
You always should try to avoid try/catch and exception throw's,
So the solution is quick and simple: if/else-statements it will be! =d
try/catch is good if the return value is abstract (can be any integer/string/etc); Otherwise, I would use if/else since it is faster and easier to check for errors. @Laslod
Quote Originally Posted by TrollerCoaster View Post
try/catch is good if the return value is abstract (can be any integer/string/etc); Otherwise, I would use if/else since it is faster and easier to check for errors. @Laslod
But what if you had a class within a class. Say :

Code:
class class1
class class2
And you wanted to operate the methods of class 2 through class 1 :

Code:
class1
{
public void DoSomething()
{
 class2.DoSomething();
}
}
Wouldn't you want to know if anything threw an exception in class 2? Since if you had if statements only in class 2, class 1 would have no way of knowing if an error occured.
If you need better performance go with if.
If you need better exception handling go with try/catch.
Or combine both./me
Posts 1–5 of 5 · Page 1 of 1

Post a Reply

Similar Threads

Talk with us