【发布时间】:2020-03-10 12:43:36
【问题描述】:
我正在尝试找出立即从其中的另一个子方法中退出方法的最佳方法。我知道我可以抛出异常,但我已经在该方法中有一个 try catch,它将捕获我抛出的任何异常。我基本上是在尝试做两次,比如 ping 服务器,如果第一次失败,捕获异常并重试,但如果第二次失败,退出整个方法。有我可以实现的 Initialize().Exit() 吗?从异常中抛出异常似乎不是最好的方法。如果初始 ping 失败或出现错误,我想捕捉,因为有时 ping 会失败,如果它执行其中任何一个,我会尝试连接到另一台服务器(未显示)。
public main()
{
bool pingedOnce = false;
try {
Initialize();
}
catch (Exception e)
{
Console.WriteLine("e");
}
}
public void Initialize()
{
try
{
if (new Ping().Send(server).Status == IPStatus.Success) //pings server to see if it exists
{
Console.WriteLine("Successfully Pinged " + server);
}
else
throw new System.Exception();
}
catch (Exception e)
{
if (!pingedOnce)) //see if server has been pinged before
{
pingedOnce = True;
Console.WriteLine("WARNING: failed to get data from server attempting to reconnect...");
ReconnectToServer(server);
}
else
throw new System.Exception("ERROR: Failed to connect to server after re-attempt.");
}
}
类似问题的另一个例子:
public Main()
{
Initialize();
}
public void Initialize()
{
foreach(string s in serverIPList)
{
for (int i=0; i<5; i++;)
{
if (new Ping().Send(serverIPList[i]).Status == IPStatus.Success) //when it finds a server that it successfully pings, it exits the method
Initialize().Exit(); //I want this to exit this for loop, the foreach loop, and the initialize method entirely.
}
}
}
理论上我可以不选择做一个 void 方法,只让它返回 null 并且从不将该方法分配给任何东西,但这比嵌套的 try catch 更好吗?
【问题讨论】:
-
为什么不在方法中
return? -
@Frontear - 听起来他们想从调用当前方法的方法返回。使用简单的
return是不可能的。 -
如果你能判断它是否成功,你不应该使用 try/catch 来处理你的第二个 ping。只需检查状态,然后重试或继续。然后你可以从初始化方法返回一个真/假(或者你想要的任何东西,真的),以便被调用者可以决定下一步做什么。
-
将 Initialize 返回类型从 void 更改为 bool 并在 main 方法中采取相应措施。
-
@Frontear 我会说“从另一个子方法中退出一个方法”似乎表明了这一点。虽然听起来确实很奇怪,但我不确定这就是 OP 的真正含义......
标签: c# exception methods ping exit-code