gpt4 book ai didi

c# - 我应该如何处理两个类之间的异常?

转载 作者:行者123 更新时间:2023-12-03 08:04:33 25 4
gpt4 key购买 nike

请参阅代码注释中的问题。

我有两个类。

这是主要类(class)(第 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() 向调用方法报告错误的最佳方式是什么?

调用者需要知道是否有错误以及错误消息是什么。我将如何发送这两条信息的调用方法?

最佳答案

删除 DivideNumbers 中的 try catch让异常冒泡。

然后将调用转至 Calculate.DevideNumbers(2, 0);在 try catch block 中。

//this class contains controls on the form.
Class MyApp
{
private void btnProcessImages_Click(object sender, EventArgs e)
{
try
{
Calculate.DevideNumbers(2, 0);
}
catch (Exception e)
{
DoStuff();
Return();
}
}
}

关于c# - 我应该如何处理两个类之间的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com