2012-03-22 97 views
1

可能重复:
How to catch exceptions的try/catch异常

我还没有真正有使用尝试和捕捉异常。我正尝试使用try/catch来捕获潜在的错误。现在我不知道在哪里把尝试,赶上这是我现在所拥有的代码..

divide d; 
    private void button1_Click(object sender, EventArgs e) 
    { 
     d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text)); 
     int total = d.CalculateDivision(); 
     MessageBox.Show(total.ToString()); 
    } 

现在我把它放在这里

try 
{ 

} 
catch 
{ 
MessageBox.Show("error"); 
} 

或我想补充的尝试/捕捉代码中的某处。

+0

在哪里的问题?什么是“新分水岭”? – gdoron 2012-03-22 09:57:02

+1

你知道try/catch有点贵。因此,您可以使用TryParse API并对上述代码进行一些重构以避免出现异常。 – Zenwalker 2012-03-22 09:57:33

+0

如果它的web应用程序可以在Global.asax中使用Application_Error事件..请参阅http://stackoverflow.com/questions/9806832/general-exception-handling-without-global-asax-file – Flowerking 2012-03-22 09:57:37

回答

2

看到http://msdn.microsoft.com/en-us/library/ms173160.aspx

try善有善报在抛出异常的代码,该值被处理。在你的例子中:

divide d; 
private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 

    d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text)); 
    int total = d.CalculateDivision(); 
    MessageBox.Show(total.ToString()); 
    } 
    catch(Exception) 
    { 
    MessageBox.Show("error"); 
    } 
} 

因为你只能显示总数,如果没有例外。

1

不,那是对的;)。 只是用它像什么,你给我们有:

try 
{ 
    // Your Code. 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex); 
} 
0

你会做这样的事情:

private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text)); 
     int total = d.CalculateDivision(); 
     MessageBox.Show(total.ToString()); 
    } 
    catch(Exception error) 
    { 
     MessageBox.Show(error.Message); 
    } 
} 
1

你很可能答案,如果有异常被抛出虽然你可以做到这一点,以获取有关更多信息,什么可能导致它:

try 
{ 
    //your code: 
    d = new divide(int.Parse(textBox1.Text), int.Parse(textBox2.Text)); 
    int total = d.CalculateDivision(); 
    MessageBox.Show(total.ToString()); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show("Error has occured! " + ex.Message); 
} 

另一个技巧为你看到你正在学习异常处理是采取看看终于块,这样会得到执行是否存在是一个例外,这是不言而喻的try和catch块后:

finally 
{ 
    // this code will always execute, maybe do some cleanup here 
}