Im not getting the throw
keyword, why use it? What are the benefits of it?
As of now I've got this in my UI class:
try
{
Classreference.MethodToRun();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This works but I guess with throw
I could make the method I am calling throw the error instead and catch it in my UI class? But why? What is better about it? Is it done to make the classes more object oriented or what? I am guessing if I just catch the error in my UI class I wont need to change the code if I change the method I am calling, but instead change the error message in the method being changed?
You use throw to indicate that an error has occured or to pass an existing error on to a higher level.
You use catch when you want to handle the error (Exception).
Throwing the exception is an improvement over the older procedural way of handling errors where you would return error codes.
The reason it is better is because you can write your logic for the simple success case, and when things go wrong you simply throw an exception, no error handling in your lower level code. It is then up to the higher levels of the application to decide what to do when a particular exception is throw.