C# 在 try-catch 子句上显示异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16145401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display Exception on try-catch clause
提问by apomene
Up to now, whenever I wanted to show an exception thrown from my code I used:
到目前为止,每当我想显示从我使用的代码中抛出的异常时:
try
{
// Code that may throw different exceptions
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I used the above code mainly for debugging reasons, in order to see the exact type of exception and the according reason the exception was thrown.
我使用上面的代码主要是出于调试的原因,以便查看异常的确切类型以及引发异常的相应原因。
In a project I am creating now, I use several try-catchclauses and I would like to display a popup message in case of an exception, to make it more "user friendly". By "user friendly", I mean a message that would hide phrases like Null Reference Exceptionor Argument Out Of Range Exceptionthat are currently displayed with the above code.
在我现在创建的一个项目中,我使用了几个try-catch子句,我想在出现异常时显示一个弹出消息,使其更加“用户友好”。通过“用户友好”,我的意思是一条消息,它将隐藏当前使用上述代码显示的诸如空引用异常或参数超出范围异常之类的短语。
However I still want to see relevant info with the type of exception that created the message.
但是,我仍然希望查看创建消息的异常类型的相关信息。
Is there a way to format the displayed output of thrown exceptions according to previous needs?
有没有办法根据以前的需要格式化抛出异常的显示输出?
采纳答案by Darren
You can use .Message, however I wouldn't recommend just catching Exceptiondirectly. Try catching multiple exceptions or explicitly state the exception and tailor the error message to the Exception type.
您可以使用.Message,但我不建议直接捕捉Exception。尝试捕获多个异常或显式声明异常并将错误消息定制为异常类型。
try
{
// Operations
}
catch (ArgumentOutOfRangeException ex)
{
MessageBox.Show("The argument is out of range, please specify a valid argument");
}
Catching Exceptionis rather generic and can be deemed bad practice, as it maybe hiding bugs in your application.
捕获Exception是相当通用的,可以被视为不好的做法,因为它可能隐藏应用程序中的错误。
You can also check the exception type and handle it accordingly by checking the Exception type:
您还可以通过检查异常类型来检查异常类型并相应地处理它:
try
{
}
catch (Exception e)
{
if (e is ArgumentOutOfRangeException)
{
MessageBox.Show("Argument is out of range");
}
else if (e is FormatException)
{
MessageBox.Show("Format Exception");
}
else
{
throw;
}
}
Which would show a message box to the user if the Exception is an ArgumentOutOfRange or FormatException, otherwise it will rethrow the Exception (And keep the original stack trace).
如果异常是 ArgumentOutOfRange 或 FormatException,它将向用户显示一个消息框,否则它将重新抛出异常(并保留原始堆栈跟踪)。
回答by User 12345678
Exception.Messageprovides a more (but not entirely) user-friendly message than Exception.ToString(). Consider this contrived example:
Exception.Message提供比Exception.ToString(). 考虑这个人为的例子:
try
{
throw new InvalidOperationException();
}
catch(InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
Although Messageyields a simpler message than ToString()the message displayed will still not mean much to the user. It won't take you much effort at all to manually swallow exceptions and display a custom message to the user that will assist them in remedying this issue.
尽管Message产生比ToString()显示的消息更简单的消息,但对用户来说仍然没有多大意义。手动吞下异常并向用户显示将帮助他们解决此问题的自定义消息根本不会花费您太多精力。
try
{
using (StreamReader reader = new StreamReader("fff")){}
}
catch(ArgumentException argumentEx)
{
Console.WriteLine("The path that you specified was invalid");
Debug.Print(argumentEx.Message);
}
catch (FileNotFoundException fileNotFoundEx)
{
Console.WriteLine("The program could not find the specified path");
Debug.Print(fileNotFoundEx.Message);
}
You can even use Debug.Printto output text to the immediate window or output window (depending on your VS preferences) for debugging purposes.
您甚至可以使用Debug.Print将文本输出到即时窗口或输出窗口(取决于您的 VS 首选项)以进行调试。
回答by Arshad
You can use Exception.Messageproperty to get a message that describes the current exception.
您可以使用Exception.Message属性来获取描述当前异常的消息。
catch (Exception ex)
{
MessageBox.Show(ex.Messagge());
}
回答by Freelancer
try
{
/////Code that may throws several types of Exceptions
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Use above code.
使用上面的代码。
Can also show custom error message as:
还可以将自定义错误消息显示为:
try
{
/////Code that may throws several types of Exceptions
}
catch (Exception ex)
{
MessageBox.Show("Custom Error Text "+ex.Message);
}
Additional :
额外的 :
For difference between ex.toString() and ex.Message follow:
ex.toString() 和 ex.Message 之间的区别如下:
Exception.Message vs Exception.ToString()
Exception.Message 与 Exception.ToString()
All The details with example:
所有细节示例:
回答by nassimlouchani
try this code :
试试这个代码:
try
{
// Code that may throw different exceptions
}
catch (Exception exp)
{
MessageBox.Show(exp.Message());
}

