例外の概要だけが必要な場合は、次を使用します。
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);
}