throw an exception in C#?

This question already has an answer here:

  • Best practices for catching and re-throwing .NET exceptions 11 answers

  • You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:

    throw;
    

    If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.

    Basically, it should be deemed a criminal offense to use "throw ex".


    My preferences is to use

    try 
    {
    }
    catch (Exception ex)
    {
         ...
         throw new Exception ("Put more context here", ex)
    }
    

    This preserves the original error, but allows you to put more context, such as an object ID, a connection string, stuff like that. Often my exception reporting tool will have 5 chained exceptions to report, each reporting more detail.


    If you throw an exception with out a variable (the second example) the StackTrace will include the original method that threw the exception.

    In the first example the StackTrace will be changed to reflect the current method.

    Example:

    static string ReadAFile(string fileName) {
        string result = string.Empty;
        try {
            result = File.ReadAllLines(fileName);
        } catch(Exception ex) {
            throw ex; // This will show ReadAFile in the StackTrace
            throw;    // This will show ReadAllLines in the StackTrace
        }
    
    链接地址: http://www.djcxy.com/p/51214.html

    上一篇: Win32:如何获得拥有互斥量的进程/线程?

    下一篇: 在C#中抛出异常?