有没有办法在捕获异常时确定它是否是使用非默认消息构造的。
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.
}
关于C# 确定异常是否用消息初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32640954/