2009-04-30 6 views
0

이 내가 설정 내 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); 
     } 
    } 

에 사용하는 코드입니다 그 함수를 두 번 호출하면 예외가 생깁니다.

문제점 - Catch {} 문 다음에 나는 예외를 잡았음에도 불구하고 finally {}를 계속 수행합니다. 그 이유는 무엇입니까? messagebox 뒤에 함수를 종료하고 싶습니다. "return"을 시도했지만 finally {} 블록을 계속 따라갑니다.

답변

3

finally 블록은 예외가 throw되었거나 try/catch 블록 내에서 메서드가 종료 된 경우에도 항상 실행됩니다.

1

finally의 전체 아이디어는 항상 예외가 발생하거나 예외가 발생하지 않는다는 것입니다. 청소 등에 사용하십시오.

1

마지막으로 블록이 항상 실행됩니다. 마침내 그게 전부입니다.

'finally'에있는 라인이 들리겠습니까?

2

finally 블록은 try 블록의 성공 여부에 관계없이 반드시 실행해야하는 코드입니다. 그것은 객체를 처분 할 수있는 코드를 "정리"하는 곳입니다.

따라서이 코드는 어떤 일이 발생했는지에 관계없이 실행됩니다. Bind가 좋을 때만 실행하려는 경우 해당 코드를 Try 블록으로 이동해야 할 수도 있습니다.

체크 아웃 페이지 ...이 작동하는 방법에 대한 자세한 내용은

http://msdn.microsoft.com/en-us/library/6dekhbbc(VS.80).aspx

....

샘플 시도/잡기/마지막으로 ... 마지막으로 항상 실행

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

(당신의 필수 독서에 있어야 C#을 통해 제프리 리히터의 CLR에서 가져온) 다음과 같습니다.

예외를 throw 할 수있는 catch 예외가 발생할 때까지 예외를 throw 한 코드 줄 다음에 존재하는 코드 만 실행됩니다.

2

다른 사람들도 지적했듯이 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... 
    } 
에 코드를 변경