这是我用来设置TCP服务器的代码

    internal void Initialize(int port,string IP)
    {
        IPEndPoint _Point = new IPEndPoint(IPAddress.Parse(IP), port);
        Socket _Accpt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            _Accpt.Bind(_Point);
        }
        catch (SocketException exc)
        {
            System.Windows.Forms.MessageBox.Show(exc.Message);

        }
        finally
        {
            _Accpt.Listen(2); //Second exception is here after the code continues after the catch block
            _Accpt.BeginAccept(null, 0, new AsyncCallback(Accept), _Accpt);
        }
    }

如果你在同一个目的地调用Bind,你会得到一个异常,因为该端口已经被使用,所以当我调用该函数两次时,我会得到那个异常。

问题 - 在Catch {}语句之后,代码继续遵循Finally {},即使我发现异常,为什么会发生这种情况? 我希望它在messagebox之后退出该函数。我尝试使用“return”,但它仍然继续跟随finally {}块。

有帮助吗?

解决方案

finally块始终执行,无论是抛出异常还是方法从try / catch块中退出。

其他提示

Finally块是放置必须运行的代码的地方,无论try块是成功还是失败。这就是你要“清理”的地方。可能处理对象等的代码。

因此,无论发生了什么,这个代码都是按照设计运行的。如果你只希望它在Bind好的时候运行,你可能需要将代码移到Try块中。

查看此页面......

http://msdn.microsoft.com/ EN-US /库/ 6dekhbbc(VS.80)的.aspx

...有关其工作原理的详细信息。

示例try / catch / finally(取自Jeffery Richter的CLR,通过C#,应该按照您的要求阅读)...

FileStream fs = null;

try
{
  fs = new FileStream(...)

  // process the data

}
catch (IOException)
{
  // inside this catch block is where you put code that recovers
  // from an IOException
}
finally
{
  // make sure the file gets closed
  if (fs != null) fs.Close();
}

正如其他人所指出的那样,无论抛出异常, finally 块总是会发生。

将您的代码更改为

    try
    {
        _Accpt.Bind(_Point);
        _Accpt.Listen(2); //Second exception is here after the code continues after the catch block
        _Accpt.BeginAccept(null, 0, new AsyncCallback(Accept), _Accpt);
    }
    catch (SocketException exc)
    {
        System.Windows.Forms.MessageBox.Show(exc.Message);

    }
    finally
    {
        //Final logging
        //Disposal of initial objects etc...
    }

finally 的整个想法是它总是会运行 - 异常或没有异常。用它来清理等。

最后总是执行块。这就是最终的重点。

听起来你在'finally'中的行可能属于try?

最终总是被执行。

只有在抛出异常的代码行之后才存在的代码才会被执行,直到遇到可以捕获异常的catch异常。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top