[英]Show message box in case of exception
我想知道將異常從一種方法傳遞到我的表單的正確方法是什么。
public void test()
{
try
{
int num = int.Parse("gagw");
}
catch (Exception)
{
throw;
}
}
形成:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
這樣,我看不到我的文本框。
如果只需要異常摘要,請使用:
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);
}
有很多方法,例如:
方法一:
public string test()
{
string ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
return ErrMsg
}
方法二:
public void test(ref string ErrMsg )
{
ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
}
try
{
// your code
}
catch (Exception w)
{
MessageDialog msgDialog = new MessageDialog(w.ToString());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.