将Called函数的异常抛出到Caller Function的Catch Block

Anu*_*jan 11 c# exception-handling 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)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码示例中,我有两个函数ReadFile和ReadCSVFile.
在ReadCSVFile中,我得到FileNotFoundExexoon类型的异常,它被catch(FileNotFoundException)块捕获.但是当我抛出此异常以捕获ReadFile()函数的catch(FileNotFoundException)时,它会捕获catch(Exception)块而不是catch(FileNotFoundException).而且,在调试时,ex的值表示为Object Not Initialized.如何将调用函数的异常抛出到调用函数的catch块而不丢失内部异常或至少发出异常消息?

PVi*_*itt 13

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

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    catch(FileNotFoundException ex)
    {
        throw;
    }
    catch(Exception ex)
    {
        throw;
    }
    finally
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

internal static string ReadCSVFile(string filePath)
{
    try
    {
        ...
        ...
    }
    finally
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

仅实现catch块:

  1. 当你想要处理异常时.
  2. 当您想通过抛出一个新的异常并将捕获的异常作为内部异常时,向异常中添加其他信息:

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

您不必在异常可以通过的每个方法中实现catch块.