2010-12-23 5 views
3

마지막으로try catch 지점이 마침내 차단됩니까?

void ReadFile(int index) 
{ 
    // To run this code, substitute a valid path from your local machine 
    string path = @"c:\users\public\test.txt"; 
    System.IO.StreamReader file = new System.IO.StreamReader(path); 
    char[] buffer = new char[10]; 
    try 
    { 
     file.ReadBlock(buffer, index, buffer.Length); 
    } 
    catch (System.IO.IOException e) 
    { 
     Console.WriteLine("Error reading from {0}. 
      Message = {1}", path, e.Message); 
    } 
    finally 
    { 
     if (file != null) 
     { 
      file.Close(); 
     } 
    } 
    // Do something with buffer... 
} 

를 사용하고 사용하지 않을의 차이점은 무엇입니까?

void ReadFile(int index) 
{ 
    // To run this code, substitute a valid path from your local machine 
    string path = @"c:\users\public\test.txt"; 
    System.IO.StreamReader file = new System.IO.StreamReader(path); 
    char[] buffer = new char[10]; 
    try 
    { 
     file.ReadBlock(buffer, index, buffer.Length); 
    } 
    catch (System.IO.IOException e) 
    { 
     Console.WriteLine("Error reading from {0}. 
      Message = {1}", path, e.Message); 
    } 

    if (file != null) 
    { 
     file.Close(); 
    } 

    // Do something with buffer... 
} 
+3

catch 블록은 오류를 다시 발생시키고 새 오류를 발생시킬 수 있습니다. 여기를 참조하십시오 - http://stackoverflow.com/questions/50618/what-is-the-point-of-theallyfin-block – StuartLC

+0

다른 사람이 내가 할 수있는 것보다 빨리 대답을 타이핑 할 것이지만, IOException 및 자신에 대한 차이를보고? – ChaosPandion

답변

7

예외가 throw되는지 또는 어떤 예외가 throw되는지에 관계없이 이전 예제에서는 file.Close()을 실행합니다.

예외가 throw되지 않거나 System.IO.IOException이 발생하는 경우에만 후자가 실행됩니다.

+0

이것은 내가 찾던 내용입니다 :) 감사합니다! – bevacqua

+0

수락 하시겠습니까? ;) –

+0

예, 그때는 할 수 없었습니다. – bevacqua

3

차이점은 finallyIOException 이외의 예외를 사용하지 않는 경우 .Close 라인에 도달되지 않습니다 때문에 응용 프로그램이 파일 핸들을 누출 될 슬로우되는 것입니다.

개인적으로 나는 항상 같은 스트림으로 처분 할 수있는 자원을 처리 할 때 using 블록을 사용 :

try 
{ 
    using (var reader = File.OpenText(@"c:\users\public\test.txt")) 
    { 
     char[] buffer = new char[10]; 
     reader.ReadBlock(buffer, index, buffer.Length); 
     // Do something with buffer... 
    } 
} 
catch (IOException ex) 
{ 
    Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message); 
} 

내가 적절하게 폐기에 대한 걱정하지 않아도 이쪽으로. try/finally는 컴파일러에서 처리하고 논리에 집중할 수 있습니다.

+0

예 방금 예제를 복사하여 붙여 넣었습니다. IOException을 지정하지 않으면 어떻게됩니까? – bevacqua

0

귀하의 경우에는 아무 것도 아닙니다. 예외를 catch 블록 밖으로 던지게하면 finally 부분은 실행되지만 다른 부분은 실행되지 않습니다.

1

catch 블록에서 예외가 발생할 수 있습니다 (path이 null 참조 인 경우를 고려하십시오). 또는 try 블록에 throw 된 예외가 System.IO.IOException이 아니므로 처리되지 않습니다. 파일 핸들은 finally을 사용하지 않는 한 두 경우 모두 닫히지 않습니다.

관련 문제