C# why throw errors [closed]

断了今生、忘了曾经 提交于 2020-01-05 13:17:31

问题


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?


回答1:


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.




回答2:


asawyer is right, you need to google and read up on error handling, it is a wide subject and you only really 'get it' after practice, talking, and reading about it. throw is something you probably won't need to use overly often, but you can occasionally use it to stop unwanted behaviour and create clearer errors for programmers using your methods. I know it is quite contrived but take this example:

public string WriteToFile(FileStream fs) {
  if (fs == null) {
    throw new ApplicationException("you passed a null filestream");
  }

  // write to file
}

You could just attempt to write the FileStream to a file without validating it, but in doing so you create a more understandable error for anyone consuming your method.




回答3:


You can use the throw keyword to throw an exception to the higher method.

Using this way, you can ocassionally make a better use of the exception, like closing database-access or something like that.




回答4:


What you are doing here is effectively masking a lot of information that you could get from the exception. what you regularly want to do is catch the exception, log the relevant information to some place where you can review it (logfile, db, eventlog) and then either throw(), which will keep you stack trace intact, or throw another "user friendly" exception which is masking the technical implementation.



来源:https://stackoverflow.com/questions/9567727/c-sharp-why-throw-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!