https://www.cnblogs.com/yao2yao4/archive/2013/01/08/2851953.html
一、基礎
1、C#中的異常處理的基本格式:
try
{
// ......
}
catch(Exception exception)
{
// ......
}
finally
{
// ......
}
一般來說finally代碼段用於處理沒有被托管的資源的釋放過程。
2、Qt中的異常處理基本格式
try
{
// ......
}
catch(QString exception)
{
// ......
}
二、異常捕獲的策略
1、try塊的范圍應該盡可能小。把代碼塊兩端的代碼逐漸剔除出去即可。
2、能夠用if語句來捕獲異常,就不要用try來捕獲。例如判斷被除數是否為0,再如判斷某個對象是否為空。
3、能夠確定具體的異常類,就不要用Exception。
4、在一個類的范圍內,為了類的完備性,對可能出錯的地方拋出異常,讓上層模塊來處理。
5、捕獲異常后,自己能夠合理處理的,自己處理掉;若是仍然沒法處理的,拋出一個新的異常對象,Message中包括當前類的類名+當前方法名、接收到的異常信息。這樣有助於調試時的定位。
1)C#
// 修正,C#有更好的處理方法
2)Qt
try
{
throw "ClassName.MethodName()";
}
catch(SQtring exception)
{
throw "NewClassName.MethodName():"+exception.Message;
}
6、最高層的的異常處理策略
1)C# Console:
C#中獲取所有異常消息的方法:
string Message(Exception exception)
{
var result = string.Empty;
if(exception != null)
{
result += exception.Message;
result += "\n";
result += exception.StackTrace;
result += "\n";
result += Message(exception.InnerException);
}
return result;
}
Console.WriteLine(Message(exception)); Console.ReadKey();
2)C# Winform:
MessageBox.Show(Message(exception)); Application.Exit();
3)Qt
QMessageBox *message=new QMessageBox();
message->setText(exception);
message->show();
return 0;

