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)
{
...
}
}
在上面的代码示例中,我有两个函数 ReadFile
和 ReadCSVFile
。
在 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 :
- 当你想处理异常时。
当您想通过抛出一个新的异常并将捕获的异常作为内部异常来向异常添加额外信息时:
catch(Exception exc) { throw new MessageException("Message", exc); }
您不必在异常可能冒出的每个方法中都实现 catch block 。
关于c# - 从 Called 函数抛出异常到 Caller Function 的 Catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7024252/