views:

610

answers:

5

I'm writing a custom class in C# and I'm throwing a couple exceptions if people give the wrong inputs in some of the methods. If the exception is thrown, will any of the code in the method after the throw still be executed? Do I have to put a break after the throw, or does a throw always quit the method?

+13  A: 

Throw will move up the stack, thus exiting the method.

jarrett
Thank you. Sorry to ask such a basic question.
Ross
+10  A: 

When you throw an exception, the next code to get executed is any catch block that covers that throw within the method (if any) then, the finally block (if any). You can have a try, a try-catch, a try-catch-finally or a try-finally. Then, if the exception is not handled, re-thrown by a catch block or not caught at all, control is returned to the caller. For example, you will get "Yes1, Yes2, Yes3" from this code ...

try
{
    Console.WriteLine("Yes1");
    throw (new Exception());
    Console.WriteLine("No1");

}
catch
{
    Console.WriteLine("Yes2");
    throw;
    Console.WriteLine("No2");
}
finally
{
    Console.WriteLine("Yes3");
}

Console.WriteLine("No3");
JP Alioto
This would be an exception (little e) to my answer. I was thinking along the lines of an Exception that would be used in the common context and not be used like a GOTO statement.
jarrett
@jarrett: This is exactly the common context, except that the throw is hidden inside function calls.
configurator
A: 

If you've wrapped your code in a Try...Catch...Finally block, then the code under Finally will always execute. For example:

Try
  ' do some stuff here
  ' Examine user input
  If user input isn't valid
      Throw new exception
Catch
   Throw ' Just re-throws the same exception
Finally
   ' This code will execute, no matter what - exception or not
End Try
rwmnau
+1  A: 

As an aside to your actual question: you might want to rethink using exceptions to provide validation info back to the user.

Raising exceptions is expensive resource-wise and slow. If you have a number of validation rules that you need to apply then write specific code for these - you should probably only rely on exception handling for things you don't anticipate.

BarneyHDog
I was wondering about this too. I'm writing a high score class, and the constructor can take a "max" param. which indicates the max score available. well if they pass a number larger than my class supports, I was throwing an exception because I didn't want the constructor to finish with bad info. I'm new at this, is there a better way to do it?
Ross
+2  A: 

I recommend stepping through your program with a debugger then you'll see for yourself what is going on. Very useful for learning!

chris166
This is a great tip. I'll do that! thanks
Ross