我怎样才能创建自己的例外?

xbo*_*nez 1 c# exception-handling

这是我的代码的骨架:

if(CheckForSomething())
{
    try
    {
        //do something
    }
    catch (UnauthorizedAccessException ex)
    {
        LogException(ex, item.server);
    }
    catch (Exception ex)
    {
        LogException(ex, item.server);
    }
}
else
{
    string error = "Some error";
    //want to call LogException with error as argument
}

private static void LogException(Exception ex)
{
    //write ex to one log file
    // write ex.message to another log file
}
Run Code Online (Sandbox Code Playgroud)

如何从else块调用LogException方法?我尝试将字符串转换为异常并创建异常.

Ste*_*end 9

一个更好的问题imo不是如何,但为什么你想要这样做?为什么不定义两个LogError重载,一个采用a Exception而另一个采用a string.

private static void LogError(Exception ex)
{
    // write ex to one log file
    // write ex.message to another log file
}

private static void LogError(string error)
{
    //nothing to write to exception-specific log file
    // write error info to another log file
} 
Run Code Online (Sandbox Code Playgroud)

为这样的Exception日志记录生成自己的实例并不可取.

  • +1为真相.不要只是回答一个不好的做法,鼓励一个好的做法. (4认同)

Jes*_*det 8

LogException(new Exception("some error"));
Run Code Online (Sandbox Code Playgroud)

  • @xbonez:虽然这确实回答了问题并且对你有用,但我真的建议你考虑其他一些答案,比如Steve Townsend和Profeten's.这个答案是一个黑客,可以让你做一些没有意义的事情.老实说,如果我正在进行代码审查并看到这样的实现,我会失去它. (4认同)