Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark a method will throw unconditionally?

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.

like image 755
k0dek0mmand0 Avatar asked Oct 05 '09 14:10

k0dek0mmand0


5 Answers

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.

like image 105
Matthew Bednarski Avatar answered Nov 15 '22 20:11

Matthew Bednarski


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);
}
like image 30
Matthew Whited Avatar answered Nov 15 '22 20:11

Matthew Whited


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." );
}
like image 22
Dan Herbert Avatar answered Nov 15 '22 18:11

Dan Herbert


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.");
}
like image 26
LukeH Avatar answered Nov 15 '22 19:11

LukeH


x is an out parameter and must be set before you move forward

like image 24
Chris Ballance Avatar answered Nov 15 '22 20:11

Chris Ballance