【发布时间】:2012-08-28 21:22:49
【问题描述】:
查看代码中的问题。
我有两节课。
这是主要课程(第 1 课):
//this class contains controls on the form.
Class MyApp
{
private void btnProcessImages_Click(object sender, EventArgs e)
{
/* if an error occurs in the method below, I want to:
1. Show the error message, and
2. Based on fail or success do different actions.
*/
Calculate.DevideNumbers(2, 0);
}
/*
if the above is successful, I want to do 1 thing,
if not, i want to do something else (with controls on THIS form).
*/
}
这是第二课:
Class Calculate
{
public double void DivideNumbers(int num1, int num2)
{
double result = 0.00;
try
{
result = num1/num2;
return result;
}
catch (Exception)
{
throw;
}
}
}
我的问题是: DivideNumbers() 向调用方法报告错误的最佳方式是什么?
调用者需要知道是否有错误以及错误消息是什么。我将如何发送这两条信息的调用方法?
【问题讨论】:
-
类 DoSomething 是否应该被命名为 Calculate 并且方法 Calculate 被命名为 DevideNumbers?
-
请澄清你的答案,将问题和代码分开。此外,您在 void 方法中返回一个 int。
-
您通常希望调用者处理异常,除非计算方法实际处理异常。
-
@C.Evenhuis,对。但是调用者实际上是如何“捕捉”这个错误的呢?例如,我需要在消息框中显示错误消息。调用者如何从其他方法的 catch 块中获取错误消息?
标签: c# exception error-handling