I have one method that looks like this:
void throwException(string msg)
{
throw new MyException(msg);
}
Now if I write
You can indicate "never returns" by using generics to declare that the function returns "anything":
T ThrowException(string msg)
{
throw new MyException(msg);
}
So now you can write:
int foo(int x, int y)
{
if (y == 0)
return ThrowException("Doh!");
else
return x/y;
}
This idiom is used in languages like Haskell and F#, and is based on the principle of explosion, also known as "ex falso quodlibet". The reasoning is this: if a function never returns, then we can make whatever magical assumptions we want about its return value, since such value will never exist. Here, the caller (foo) assumes ThrowException will return an int.
A few minor drawbacks:
ThrowException
can circumvent this by returning default(T)
.ThrowException
(Haskell and F# can infer it).As the other answers say, you're probably better off returning the exception rather than throwing it.