在捕获异常时是否有办法确定它是否是由非默认消息构造的
try
{
throw new Exception(message); // case 1
//throw new Exception(); // case 2
}
catch(Exception exp)
{
/* what do I put here such that if the case 2 exception were
caught it would output exp.ToString() instead of exp.Message? */
textBox1.Text = exp.Message; // case 1 handeling
}
只是为了澄清当抛出Exception(message)时,我希望它输出exp.Message,而当抛出Exception()时,我希望输出exp.ToString()。我希望在不添加自定义异常的情况下完成此任务。谢谢。
您需要检查消息是否存在默认异常
catch (Exception e)
{
bool isDefaultMessage = e.Message == new Exception().Message;
}
异常的不同类型
catch (Exception e)
{
bool isDefaultMessage = false;
try
{
var x = (Exception) Activator.CreateInstance(e.GetType());
isDefaultMessage = e.Message == x.Message;
}
catch (Exception) {} // cannot create default exception.
}