55pizzas
55pizzas

Reputation: 45

How to reuse exception throwing code to return a boolean?

Lets say I have a block of if statements that throw an exception if the conditional is true. How can I create a method that uses those same conditionals, but returns a true or false instead of throwing the exceptions. ie, if an exception is thrown, return false; if an exception isnt thrown then return true. I want to reuse as much of the code as possible.

I also would want to try to avoid simply catching all exceptions I'm throwing.

edit:sorry typos

Upvotes: 0

Views: 939

Answers (2)

supercat
supercat

Reputation: 81149

Have the common code accept a delegate which will be invoked if the bad condition arises (probably a function which returns false). Then:

  if (SomethingBadHappened)
    return ReportSomethingBad(new ImNotFeelingWellException("I'm not feeling too well..."));

The "TryDoingSomething" version of the routine (which should return False rather than throwing an exception) should invoke the common version with a delegate that does nothing but return false. The "DoSomethingAndThrowExceptionIfItFails" version should invoke the common routine with a delegate that will throw the passed-in exception.

Doing things that way will allow the exceptions to contain much more useful information than would be possible if they were simply generated by a TryDoingSomething() routine that returned false.

Upvotes: 0

SLaks
SLaks

Reputation: 887415

Move the code into a function that returns the boolean, then change the original function to call the new one and throw an exception if it returns false.

Upvotes: 2

Related Questions