I am trying to wrap my exception throwing logic into another class so that it is easier to throw custom exceptions. Every class would use either a direct reference to this Thrower class, or an interface, whatever is most appropriate.
I have written a simple class that handles it and it works for the most part, but I have encountered a situation in methods with return types where, even though an exception will always be thrown, the compiler fails to detect it and complains that not all paths return a value.
The following code shows an simplified form of the structure of the Thrower class and any class which would use said Thrower.
public class Thrower
{
public void ThrowException()
{
throw new Exception("Im an exception");
}
}
public class Foo
{
// Does not work, compiler complains about not all paths returning values.
public int ExceptionNotDetected(bool shouldThrow)
{
if (!shouldThrow)
{
return 1;
}
var thrower = new Thrower();
thrower.ThrowException();
}
// Works fine.
public int ExceptionDetected(bool shouldThrow)
{
if (!shouldThrow)
{
return 1;
}
throw new Exception("Im an exception");
}
}
As far as I can see the method that uses the Thrower must either return a value or throw an exception. From that it seems that the method ExceptionNotDetected and ExceptionDetected are functionally equivalent.
Why then does the compiler complain about ExceptionNotDetected?
Edit:
In regards to the design, this was purely for illustration purposes as all I really wanted to do is understand what was happening. I apologize if I didn't clarify this properly in the post description. That being said I appreciate the advice in regards to structure.