views:

387

answers:

7

I have an if condition which checks for value and the it throws new NumberFormatException

Is there any other way to code this

if (foo)
{
    throw new NumberFormatException
}

// ..

catch (NumberFormatException exc)
{
    // some msg...
}
+5  A: 

GustlyWind, my brain just threw QuestionUnreableException. Please clarify.

aku
Clever ! Plus one !
wcm
+1  A: 

If your aim is to avoid to throw a new exception:

if(foo)
{
  //some msg...
} else
{
  //do something else
}
Burkhard
A: 

In Java, you can try parsing a string with regular expressions before trying to convert it to a number.

If you're trying to catch your own exception (why???) you could do this:

try { if (foo) throw new NumberFormatException(); }
catch(NumberFormatexception) {/* ... */}
Mark Cidade
You could have fit more code on one line. It's still way to readable (note: sarcasm). :-)
Till
+4  A: 

If you are doing something such as this:

try
{
   // some stuff
   if (foo)
   {
      throw new NumberFormatException();
   }
}
catch (NumberFormatException exc)
{
   do something;
}

Then sure, you could avoid the exception completely and do the 'do something' part inside the conditional block.

itsmatt
A: 

if you are trying to replace the throwing of an exception with some other error handling mechanism your only option is to return or set an error code - the problem is that you then have to go and ensure it is checked elsewhere.

the exception is best.

dice
+1  A: 

Don't throw exceptions if you can handle them in another, more elegant manner. Exceptions are expensive and should only be used for cases where there is something going on beyond your control (e.g. a database server is not responding).

If you are trying to ensure that a value is set, and formatted correctly, you should try to handle failure of these conditions in a more graceful manner. For example...

if(myObject.value != null && Checkformat(myObject.Value)
{
    // good to go
}
else
{
    // not a good place to be.  Prompt the user rather than raise an exception?
}
ZombieSheep
A: 

If you know the flow that will cause you to throw a NumberFormatException, code to handle that case. You shouldn't use Exception hierarchies as a program flow mechanism.

Nate