2013-12-21 75 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()); 
    }