将被调用函数的异常抛出到调用函数的 Catch 块
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) 块捕获。但是,当我抛出此异常以在 ReadFile 函数的 catch(FileNotFoundException) 中捕获时,它会在 catch(Exception) 块中捕获,而不是在 catch(FileNotFoundException) 中捕获。此外,在调试时,ex 的值显示为“对象未初始化”。如何将异常从被调用函数抛出到调用者函数的 catch 块而不丢失内部异常或至少异常消息?
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)
{
...
}
}
Here in the above code sample, I have two functions ReadFile
and ReadCSVFile
.
In the ReadCSVFile
, I get an exception of type FileNotFoundException, which gets caught in the catch(FileNotFoundException) block. But when I throw this exception to be caught in the catch(FileNotFoundException) of the ReadFile
Function, it gets caught in the catch(Exception) block rather than catch(FileNotFoundException). Moreover, while debugging, the value of the ex says as Object Not Initialized. How can I throw the exception from the called function to the caller function's catch block without losing the inner exception or atleast the exception message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须使用
throw; 而不是
throw ex; :
除此之外,如果您在 catch 块中除了重新抛出之外不执行任何操作,则根本不需要 catch 块:
实现 catch 块
当您想通过抛出一个新异常并将捕获的异常作为内部异常来向异常添加附加信息时:
catch(Exception exc) { throw new MessageException("Message", exc); }
您不必在每个可能出现异常的方法中实现 catch 块。
You have to use
throw;
instead ofthrow ex;
:Besides that, if you do nothing in your catch block but rethrowing, you don't need the catch block at all:
Implement the catch block only:
when you want to add additional information to the exception by throwing a new exception with the caught one as inner exception:
catch(Exception exc) { throw new MessageException("Message", exc); }
You do not have to implement a catch block in every method where an exception can bubble through.
只需在被调用的函数中使用 throw 即可。不要重载具有多种异常类型的 catch 块。让呼叫者来处理这个问题。
Just use throw in the called function. Dont overload catch blocks with multiple exception types. Let the caller take care of that.
你应该替换
为
You should replace
by
在被调用函数中只需使用 throw 这样的方法
现在,如果此处出现异常,则调用函数将捕获该异常。
In the called function just use throw like this
Now, if the exception arise here then this will be caught by the caller function .
您的代码在这里工作正常,请检查此处 http://ideone.com/jOlYQ
Your code works fine here, Check here http://ideone.com/jOlYQ