How to mark a method will throw unconditionally?
It's a very old thread but I just want to add you should write it different from the start:
void foo(out int x)
{
if (!condition())
MyMethodThatAlwaysThrowsAnException("missed something.");
x = bar();
// and so on...
}
That way compiler won't complain and your code is much more clear.
How about this?
bool condition() { return false; }
int bar() { return 999; }
void foo(out int x)
{
if (condition()) { x = bar(); return; }
// compiler complains about x not being set yet
throw MyMethodThatAlwaysThrowsAnException("missed something.");
}
Exception MyMethodThatAlwaysThrowsAnException(string message)
{
//this could also be a throw if you really want
// but if you throw here the stack trace will point here
return new Exception(message);
}
If you know the exception will always be thrown, why does it matter. Just set the variable to something so it can compile:
void foo(out int x)
{
if( condition() ) { x = bar(); return; }
x = 0;
MyMethodThatAlwaysThrowsAnException( "missed something." );
}
There's no way of marking a method in this way.
Possibly irrelevant, but the pattern in your example, using an out
parameter, is a bit odd. Why not just have a return type on the method instead?
int Foo()
{
if (condition()) return bar();
MyMethodThatAlwaysThrowsAnException("missed something.");
}