The performance hit is most probably negligible, as explained in this answer.
So let's go with the idea that performance isn't an issue. You're throwing System.Exception
, just to move execution into the catch
clause. Throwing a BadControlFlowThatShouldBeRewrittenException
would probably be overkill though.
Let's break this down. We have:
- Method
GetDataFromServer
(method names should be PascalCase in C#), which can possibly throw an exception, or return a bool
.
- If result was
true
, run ProcessData
.
- Return
null
otherwise.
Looks like the method where this code is written, is simply doing too many things. GetDataFromServer
returning a bool
looks like a design flaw, I'd be expecting that method to return the data it's getting from the server, some IEnumerable<SomeType>
that would contain 0 or more items - i.e. happy path returns n items where n > 0, not-so-happy path returns 0 items, and unhappy path blows up with an unhandled exception, whatever that is.
That changes what the method looks like, quite a lot - again it's hard to tell whether this makes sense, because the original post only has one exit point (and thus wouldn't compile, as not all code paths return a value), so this is only a wild guess:
try
{
var result = GetDataFromServer();
return ProcessData(result);
}
catch
{
return null;
}
Here you'd look at ProcessData
and see that it's iterating the result
, and returns null
if there's no item in the IEnumerable
.
Now why is the method returning null
? Server was down? Is there a bug in the query? The connection string is using the wrong credentials? Whenever GetDataFromServer
blows up with an exception you're not expecting, you're swallowing it, shoving it under the carpet and returning a null
value. I'd recommend catching specific exceptions in this case, and log everything else; debugging will be much easier that way.
With a general catch
clause that doesn't capture the exception, it gets pretty hard to diagnose anything. I'd minimally do this instead:
catch(Exception e)
{
return null;
}
Now you can at least break and inspect e
if things go wrong.
TL;DR: No, throwing and catching exceptions for flow control isn't a good idea.