如果您只想要异常的摘要,请使用:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
如果您想查看整个堆栈跟踪(通常更适合调试),请使用:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
我有时使用的另一种方法是:
private DoSomthing(int arg1, int arg2, out string errorMessage)
{
int result ;
errorMessage = String.Empty;
try
{
//do stuff
int result = 42;
}
catch (Exception ex)
{
errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
result = -1;
}
return result;
}
在您的表格中,您将拥有以下内容:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}