我正在尝试找出立即从该方法的另一个子方法中退出该方法的最佳方法。我知道我可以抛出异常,但是我已经在该方法内部有了一个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更好的做法吗?
如果您要坚持使用异常处理设计,建议您创建一个自System.Exception
派生的自定义类。您几乎不应该抛出System.Exception
;而是抛出一个更专业的异常,这使您能够以不同方式捕获和处理每种类型的异常。例如:
try
{
// this can throw different kinds of exceptions.
}
catch (InvalidOperationException e)
{
// do something.
}
catch (ArgumentException e)
{
// do something different.
}
如果有异常抛出。否则返回!
if (new Ping().Send(server).Status == IPStatus.Success) //pings server to see if it exists
{
Console.WriteLine("Successfully Pinged " + server);
return; //RETURN here if you dont want to do anything!
}
else
throw new System.Exception();
并且无论在哪里都一样。因此,如果发生异常或方法将在所需的位置停止,您可以捕获异常。