Search code examples
c#exceptiontry-catchfinally

problem in try statement


This is the code I use to setup my TCP server

    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);
        }
    }

If you call Bind on the same destination you'll get an exception,because the port is already in use,so do I get that exception when I call that function two times.

Problem - After Catch{} statement the code continues to follow the Finally{} even though I caught the exception,why that happens? I want it to exit the function after the messagebox.I tried with "return",but it still continues to follow the finally{} block.


Solution

  • The finally block always executes, regardless if an exception was thrown or the method was exiting from within the try/catch block.