2013-12-21 114 views
0
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      string[] names = new string[2]; 
      string g = names[2]; 
     } 
     catch(Exception error) { 
      MessageBox.Show(error); 
     } 
    } 
} 

我不知道最近怎麼了,它似乎找不到錯誤。如果你能幫助我,這會有幫助嗎?異常消息不能正常工作

+1

您看到了什麼結果? –

回答

3

Show沒有超載,它接受Exception作爲參數。你可能想顯示異常的Message屬性:

try 
{ 
    string[] names = new string[2]; 
    string g = names[2]; 
} 
catch(Exception error) 
{ 
    MessageBox.Show(error.Message); 
} 

// Index was outside the bounds of the array. 

或者可能調用ToString,通常會爲您提供的不僅僅是Message多一點信息:

try 
{ 
    string[] names = new string[2]; 
    string g = names[2]; 
} 
catch(Exception error) 
{ 
    MessageBox.Show(error.ToString()); 
} 

// System.IndexOutOfRangeException: Index was outside the bounds of the array. 
// at Form1.button1_Click(Object sender, EventArgs e) in ...Form1.cs:line 35 
0

你不能訪問index 2爲索引從0開始

string g = names[2];//index2 is invalid 

您可以使用ToString()獲取所有異常詳細信息

catch(Exception error) { 
     MessageBox.Show(error.ToString()); 
    }