异常消息不起作用

时间:2013-12-21 01:46:25

标签: c# exception

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);
        }
    }
}

我不知道它的错误似乎无法找到错误。如果你可以帮助我会有帮助吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您无法访问index 2,因为索引从0开始

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

您可以使用ToString()来获取所有异常详细信息

 catch(Exception error) {
        MessageBox.Show(error.ToString());
    }
相关问题