문제

Sometimes I dont know witch type of exception should I throw. So I usually throw Exception(). Is there some nice article about this?

도움이 되었습니까?

해결책

If you are not making any attempt to recover from an error, you can just throw an Exception with a string to tell you what went wrong. (Or if you will perform the same action regardless of what error occurred).

Other than making it obvious to a programmer what went wrong by using a new exception name rather than putting it in the Message, and exception can contain data to help you recover from a particular exception.

For example, an ArgumentNullException has a property ParamName, which you should set when you throw the exception. When the caller catches it, he can then look up this property and decide to pass a new value for the argument which caused the error, or can print a relevant error to inform the programmer what went wrong.

It's unfortunate that exceptions are rarely used to their full potential (in many open source APIs and such), and are often simply inserted to inform a programmer what went wrong. There's not much difference between these 2 if you don't plan to read the ParamName property when you catch it. (Many people will not bother, and only catch an Exception anyway).

throw new ArgumentNullException("arg1");
throw new Exception("arg1 is null");

It can be difficult to recover from an error fully, but in some applications though, you might find it desirable to create custom exceptions which can provide all the details you need.

For now, I would just put Exception into the Object browser search in VS, and see what is there already. Their names are pretty self explanatory, so you should be able to pick out something suitable.

다른 팁

The problem with throwing a generic exception is that it restricts the ability of your code further up the stack to handle it properly (i.e. best practice is to trap the most specific exception possible before falling back, and to only capture what you can handle).

Jeffrey Richter has an excellent section on exception handling (including info on the System.Exception namespace) in CLR via C#

"Framework Design Guidelines" by Cwalina and Abrahms covers this topic really well (IMHO).

It is available for free online here, or the book (not free) here (UK) or here(US). Look in the section entitled Design Guidelines for Exceptions.

Well, the one thing you shouldn't do is throw Exception itself.
Always look for an appropriate subclass.

I don't know of any publication spelling out which exception to throw when, but ArgumentException and InvalidOperationException should take care of most of your cases.

Ask separate questions about separate cases if they come up.

I would suggest dividing exceptions into a few categories based upon the system state:

  1. The method failed in such a fashion that it did nothing; the state of any underlying data was not disturbed, and is probably valid. Typical scenarios: trying to retrieve from a collection an object which isn't there, or add one which already is. Another possible scenario: a communications timeout in cases where it should not have caused any data loss (and were retrying the operation might succeed if the problem was simply that the other end was simply too slow).
  2. The method failed in a fashion which may have disturbed the underlying data structure, or the underlying data structure may have been corrupted previously. Further operations should not be attempted with this data structure unless steps are taken to validate it. Another possible scenario: a communications timeout occurs when a record has been partially retrieved, and the partially-retrieved data is now lost. Depending upon the protocol, it may be necessary to perform some recovery action on the connection, or to close it and initiate a new one.
  3. Something is seriously wrong with the system state, and recovery is likely not possible.

Unfortunately, existing .net exceptions don't fit anything like that pattern; it would have been nice if there were a type ExceptionBase from which things like ThreadAbortException, CpuHasCaughtFireException, and the 'normal' Exception were derived, and all 'normal' exceptions were derived from Exception. I understand that .net 4.0 somewhat kludges in such a design, but I don't know the exact mechanics. In any case, I would suggest that any user-defined exceptions should be divided into groups as above, with all exceptions in each group sharing a common ancestor distinct from other groups.

There's an article by Krzysztof Cwalina ("a Principal Architect on the .NET Framework team at Microsoft") called Choosing the Right Type of Exception to Throw that sheds some light on this. It deals with choosing the right exception to throw and guidance on creating custom exceptions.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top