代码之家  ›  专栏  ›  技术社区  ›  Shrewdroid

C中异常中的异常处理#

  •  5
  • Shrewdroid  · 技术社区  · 16 年前

    我知道这可能有点奇怪,但怀疑毕竟是一种怀疑。。。

    private void SendMail()
    {
        try
        {
            //i try to send a mail and it throws an exception
        }
        catch(Exception ex)
        {
            //so i will handle that exception over here
            //and since an exception occurred while sending a mail
            //i will log an event with the eventlog
    
            //All i want to know is what if an exception occurs here
            //while writing the error log, how should i handle it??
        }
    }
    

    非常感谢。

    8 回复  |  直到 12 年前
        1
  •  4
  •   Robben_Ford_Fan_boy    16 年前

    我个人会用另一个try\catch语句包装调用以写入事件日志。

        2
  •  4
  •   Chris S    16 年前

    您可以简单地在错误日志记录方法中捕获错误。不过,我个人不会这么做,因为错误日志记录中断是应用程序无法正常运行的标志。

    private void SendMail()
    {
        try
        {
            //i try to send a mail and it throws an exception
        }
        catch(Exception ex)
        {
            WriteToLog();
        }
    }
    
    private void WriteToLog()
    {
        try
        {
            // Write to the Log
        }
        catch(Exception ex)
        {
            // Error Will Robinson
            // You should probably make this error catching specialized instead of pokeman error handling
        }
    }
    
        3
  •  1
  •   VoodooChild    16 年前

    只有在try-catch块中时,才会捕获每个异常。你可以尝试捕捉,但通常不是一个好主意。

        4
  •  0
  •   thelost    16 年前

    try-catch 挡在你的车里 catch 也要封锁。

        5
  •  0
  •   Sylvestre Equy    16 年前

    考虑到写入文件时的例外情况(权限、磁盘空间…),我建议不要在这里处理它。如果第一次失败,很有可能您无法写入事件日志,而无法写入事件日志。。。

    让它冒泡起来,由上层的try/catch来处理。

        6
  •  0
  •   Peter    16 年前

    克里斯S。有最好的答案。在catch块中放置try-catch块很少是个好主意。在你的情况下,它只会让你的代码变得复杂。如果您在此处检查是否成功写入日志文件,则必须在尝试写入日志文件的每个位置都执行此操作。在通知/处理这些模块中的错误条件时,您可以轻松地避免这种不必要的代码重复,方法是让所有单个模块都是独立的。当发送邮件失败时,您可以在catch块中执行适当的操作来处理这种异常情况,如:

    1. 处理邮件对象的内容
    2. 确保你的插座是关闭的

    在catch块中,只需调用您定义的任何API就可以将日志条目写入日志文件,其余的就不用管了。在日志API中,您应该处理任何与日志相关的异常情况(磁盘已满、没有写入文件的权限、找不到文件等)。您的邮件模块不需要知道日志记录是否成功,应该将该职责委派给日志记录模块。

        7
  •  0
  •   drharris    16 年前

    public static class MyExtentions
    {
        public static void LogToErrorFile(this Exception exception)
        {
            try
            {
                System.IO.File.AppendAllText(System.IO.Path.Combine(Application.StartupPath, "error_log.txt"),
                    String.Format("{0}\tProgram Error: {1}\n", DateTime.Now, exception.ToString()));
            }
            catch 
            { 
                // Handle however you wish
            }
        }
    }
    

    try
    {
       ...
    }
    catch(Exception ex)
    {
       ex.LogToErrorFile();
    }
    

        8
  •  0
  •   Community Mohan Dere    9 年前
    推荐文章