显示消息框,以防异常 [英] Show message box in case of exception
本文介绍了显示消息框,以防异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道正确的方法是将异常从一种方法传递给我的表单。
I'm wondering what the correct way is to pass on an exception from one method to my form.
public void test()
{
try
{
int num = int.Parse("gagw");
}
catch (Exception)
{
throw;
}
}
表单:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
这样我看不到我的文本框。
in this way i cannot see my text box.
推荐答案
如果您只想使用异常的摘要:
If you want just the summary of the exception use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
如果要查看整个堆栈跟踪(通常更适合调试)使用:
If you want to see the whole stack trace (usually better for debugging) use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
我有时使用的另一种方法是:
Another method I sometime use is:
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;
}
在您的表单中,您将有以下内容:
And In your form you will have something like:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}
这篇关于显示消息框,以防异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文