如何管理catch块中的异常

本文关键字:异常 catch 何管理 管理 | 更新日期: 2023-09-27 18:10:49

我有以下代码:

try
{
    int s=10;
    int k=0;
    int stdsd = s / k;
}
catch (DivideByZeroException ext)
{
    FileStream fs = new FileStream(@"C:'temp'data.txt", FileMode.Open);  
    //encountered an exception as file doesn't exist.
}
catch (Exception ex)
{
}
finally
{
    //some code here.
}

在上面的代码中,当异常发生时,它将尝试将其写入catch块中的一个文件中。但是当它试图打开该文件时,该文件不存在,所以在这种情况下系统崩溃。我想在finally块中执行这样的关键代码,但由于catch块中的异常,它没有进一步执行到那一行。

我知道我们可以检查文件是否存在但我不想检查文件是否存在,我想知道如何在catch块中管理它。

如何管理catch块中的异常

您无法处理与相同try/catch语句关联的catch块中一个catch块生成的异常。相反,您需要一个额外的:

catch (DivideByZeroException ext)
{
    try
    {
        FileStream fs = new FileStream(@"C:'temp'data.txt", FileMode.Open);  
    }
    catch (IOException e)
    {
        // Handle the exception here
    }
}

注意,在打开流时应该使用using语句,这样无论以后是否抛出异常,都可以自动关闭流。

我还建议不要在直接在catch块中使用这样的代码-通常catch块应该很短,为了可读性。考虑将所有错误处理功能移动到一个单独的方法(甚至可能是一个单独的类)中。

就用另一个try {} catch {}

try { 
    // ...
    try {
        // try opening your file here ...
    } catch (Exception) {
        // ...
    }
} catch (Exception) {
    // ...
}

如果你不想检查文件"over here"是否存在(在异常中),那么你可以选择检查"over there"是否存在,即:在代码的前面。

你要做的是写一个异常日志到一个文件,正如我所理解的。因此,您可以在代码的早期配置正确的日志文件处理,在最好的情况下使用一个好的日志文件处理程序。在此之后,您在异常处理程序中唯一要做的事情就是将异常消息推送到日志处理程序-然后它将正确地将此信息写入文件。

异常对于任何语言来说都是非常强大的未来,在大多数情况下都不能被忽略,但如果可能的话请尽量避免

看这个

            String File = "File.txt";
            System.IO.FileInfo fileinfo = new System.IO.FileInfo(File);
           if(fileinfo.Exists)
           {
               using (System.IO.FileStream file = new System.IO.FileStream(File, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
             {
                 // operation on file here
             }
           }else
           {
               using (System.IO.FileStream file = new System.IO.FileStream(File, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
               {
                   // operation on file here now the file is new file 
               }
           }