c# - 从 Called 函数抛出异常到 Caller Function 的 Catch block

标签 c# exception try-catch-finally

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    catch(FileNotFoundException ex)
    {
        throw ex;
    }
    catch(Exception ex)
    {
        throw ex;
    }
    finally
    {
        ...
    }
}


//Reading File Contents

public void ReadFile()
{
    try
    {
        ...
        ReadCSVFile(filePath);
        ...
    }
    catch(FileNotFoundException ex)
    {
        ...
    }
    catch(Exception ex)
    {
        ...
    }
}

在上面的代码示例中,我有两个函数 ReadFileReadCSVFile
ReadCSVFile 中,我得到一个 FileNotFoundException 类型的异常,它在 catch(FileNotFoundException) block 中被捕获。但是,当我抛出此异常以在 ReadFile 函数的 catch(FileNotFoundException) 中捕获时,它会在 catch(Exception) block 中捕获,而不是在 catch(FileNotFoundException) 中捕获。此外,在调试时,ex 的值显示为对象未初始化。如何在不丢失内部异常或至少异常消息的情况下将异常从被调用函数抛出到调用函数的 catch block ?

最佳答案

你必须使用 throw; 而不是 throw ex;:

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    catch(FileNotFoundException ex)
    {
        throw;
    }
    catch(Exception ex)
    {
        throw;
    }
    finally
    {
        ...
    }
}

除此之外,如果你在你的 catch block 中除了重新抛出什么都不做,你根本不需要 catch block :

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    finally
    {
        ...
    }
}

只实现 catch block :

  1. 当你想处理异常时。
  2. 当您想通过抛出一个新的异常并将捕获的异常作为内部异常来向异常添加额外信息时:

    catch(Exception exc) { throw new MessageException("Message", exc); }

您不必在异常可能冒出的每个方法中都实现 catch block 。

关于c# - 从 Called 函数抛出异常到 Caller Function 的 Catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7024252/

相关文章:

java - 如何避免在我的情况下返回 null?

c# - 2000 个工作线程,只有很少的实际线程

c# - Unity格式化多个数字

c++ - 为什么 SIGSEGV 的信号处理程序无法捕获我的 C++ 抛出异常?

java - 我应该在虚线上捕获什么异常?

java - 为什么finally block 执行与未捕获的异常不一致

c# - 添加继承时删除 ':' 之前的换行符

c# - 标记类的接口(interface)或属性?

c# - WPF C# WebView 在 win 10 上不显示任何页面

c# - 同时使用 catch 和 finally 的 try-catch-finally 的用例