我们经常在方法中使用try catch语句,如果方法可以返回一个值,但该值不是字符串,如何返回异常消息? 例如:
public int GetFile(string path)
{
int i;
try
{
//...
return i;
}
catch (Exception ex)
{
// How to return the ex?
// If the return type is a custom class, how to deal with it?
}
}
如何返回异常?
最佳答案
如果您想在 catch block 中执行一些有用的操作(例如记录异常),则可以删除
try catch block 以引发异常,或者从 catch block 中抛出
异常。如果您想从您的方法发送异常消息并且不想抛出异常,那么您可以使用 out 字符串变量,用于保存调用方法的异常消息。
public int GetFile(string path, out string error)
{
error = string.Empty.
int i;
try
{
//...
return i;
}
catch(Exception ex)
{
error = ex.Message;
// How to return the ex?
// If the return type is a custom class, how to deal with it?
}
}
如何调用该方法。
string error = string.Empty;
GetFile("yourpath", out error);
关于c# - try catch 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14064785/