Craig Johnston
Craig Johnston

Reputation: 7607

C#: does 'throw' exit the current function?

If there is a throw statement in the middle of a function, does the function terminate at this point?

Upvotes: 12

Views: 16181

Answers (7)

Michael Petrotta
Michael Petrotta

Reputation: 60942

Control passes to the next exception handler (catch block) in the call stack, whether that be in the current method or one of its parents. If the throw is not encapsulated in a try/catch block, any finally blocks are executed before a parent catch block is sought.

Upvotes: 7

PedroC88
PedroC88

Reputation: 3829

An exception is an event that happened when it wasn't supposed to and so the application does not know what to do with such event. In all OOP languages (that I know of) what the runtime does is to halt the function that called the event and then throw the Exception up the stack until someone knows what to do with it. That is where try / catch blocks come in.

Upvotes: 0

Holstebroe
Holstebroe

Reputation: 5133

Yes, unless you catch it or have a finally block:

try {
   var foo = 42 /0;
}
finally
{
  // This will execute after the exception has been thrown
}

Upvotes: 1

Dave
Dave

Reputation: 15016

Did you try it? :)

I guess the right answer is, it depends. If you wrapped the throw with a try/catch for whatever strange reason, then no. If you didn't, then yes, unless you didn't catch the exception somewhere up the call stack, in which case your entire application would crash.

Upvotes: 1

nybbler
nybbler

Reputation: 4841

Yes. It will go to the nearest catch block.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994131

Yes, with the exception of any finally blocks, or if there is an exception handler within the function that can catch the type of exception you're throwing.

Upvotes: 18

FarligOpptreden
FarligOpptreden

Reputation: 5043

It does, yes. It generates an exception that goes up the calling stack.

Upvotes: 0

Related Questions