The documentation I've found is a little hazy on this subject, so it's time to fire off yet another no-doubt ignorant question:
Is "throw" intended exclusively for the following scenario: Control is transferred out of a try block via a method call, and code in the called method then detects an exception, so the called method uses "throw" to transfer control back to the appropriate catch block associated with the original try block?
Posted Feb 3, 2009, 4:10 PM
public bool NameIsMine(string name)
{
if (!String.IsNullOrEmpty(name))
{
return name == "Brandon";
}
else
throw new NullReferenceException("Unable to check name, name has no value.");
}
Now say you have some code that calls this method:
private void btnClick(object sender, EventArgs e)
{
bool isMyName;
try
{
isMyName = NameIsMine(null); // Uh-oh, exception will get thrown!
}
catch (NullReferenceException ex) // Exception gets caught here
{
MessageBox.Show(ex.Message, "Invalid Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You have a try-catch surrounding the code that may throw an exception. So long as you have a catch block that can handle the exception, your good to go. However, lets say for instance that you didnt:
private void btnClick(object sender, EventArgs e)
{
bool isMyName;
try
{
isMyName= NameIsMine(null); // Uh-oh, exception will get thrown!
}
catch (IOException ex) // Exception wont get caught, not the right exception type
{
MessageBox.Show(ex.Message, "Invalid Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
What happens now? Well, since there are no catch blocks capable of handling an exception type of NullReferenceException, it will get propagated until it encounters one that CAN handle it. If it doesnt find any, fun stuff happens like the exception being bubbled up to the user interface as an unhandled exception and since threads in .NET terminate when an exception is propogated to the end of the call stack with no handlers, you can probably guess what happens next...
So in summary, throwing an exception is similar to returning something from a method (function for you C++ guys), except it has to be caught and handled in an appropriate catch block