Is there a way to decorate a method that will do some logging, then throw an exception unconditionally, as such?
I have code like this:
void foo(out int x)
{
if( condition() ) { x = bar(); return; }
// notice that x is not yet set here, but compiler doesn't complain
throw new Exception( "missed something." );
}
If I try writing it like this I get a problem:
void foo(out int x)
{
if( condition() ) { x = bar(); return; }
// compiler complains about x not being set yet
MyMethodThatAlwaysThrowsAnException( "missed something." );
}
Any suggestions? Thanks.
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.");
}
x
is an out parameter and must be set before you move forward
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With