2014-11-19 4 views
1

이 코드를 컴파일 할 때 writerSaveArray의 할당되지 않은 로컬 변수라는 컴파일 오류가 발생합니다. 유사한 방법 LoadArray에서 reader에 대해 불평하지 않습니다. 왜 이런 경우입니까? 그들은 똑같은 행동을해야하지 않습니까? new StreamWriter(fileName);가 예외를 throw하면로컬 변수가 한 방법에 할당되었지만 거의 동일한 방법으로 할당되지 않은 이유는 무엇입니까?

static void SaveArray(string fileName, string[,] arr) 
    { 
     StreamWriter writer; 
     try 
     { 
      writer = new StreamWriter(fileName); 
     } 
     catch 
     { 
      MessageBox.Show("Error, could not open " + fileName + " for saving"); 
     } 
     try 
     { 
      foreach (string entry in playerArray) 
      { 
       writer.WriteLine(entry); 
      } 
     } 
     catch 
     { 
      MessageBox.Show("Couldn't save"); 
     } 
     writer.Close(); 
    } 

    static void LoadArray(string fileName, string[,] arr) 
    { 
     StreamReader reader; 

     try 
     { 
      reader = new StreamReader(fileName); 
     } 
     catch 
     { 
      MessageBox.Show("Error when reading file" +fileName); 
      return; 
     } 


     try 
     { 
      for(int i=0; i<=arr.GetUpperBound(0); ++i) 
      { 
       for (int j = 0; j<=arr.GetUpperBound(1); ++j) 
       { 
        arr[i, j] = reader.ReadLine(); 
       } 
      } 

     } 
     catch 
     { 
      MessageBox.Show("Could not read from file " +fileName); 
     } 
     reader.Close(); 
    } 

답변

4

s는 할당되지 않은 유지됩니다.

s.WriteLine(entry);에서 사용하려고하면 오류가 발생합니다.

그리고 로 @DarrenYoung

catch에서, LoadArray 반환 댓글을 달았습니다, 그래서 x.ReadLine()에서 x 초기화 할 수 보장됩니다.

+1

이제 'x'버전이 정상인 이유를 설명합니다. –

+2

@LeeTaylor 첫 번째 catch 블록에서 LoadArray 메서드를 반환하기 때문입니다. –

+0

다른 방법으로 항목을 s.WriteLine 할 수 있습니까? –

2

LoadArray에서 캐치 예외가 발생하면 리더가 사용되기 전에 메서드가 반환됩니다. SaveArray에서 예외를 잡았지만 작성자가 할당을 완료하지 못했지만 명랑한 방법으로 계속됩니다.

잡힌 예외가 즉시 정상적인 제어 흐름에서 벗어 났으므로 현재 명령문 실행이 완료되지 않습니다.

1

Writer라는 StreamWriter 객체를 어떻게 선언하는지 알지만 try/catch 블록을 입력해야 초기화됩니다. try catch가 실패하면 어떻게됩니까?

 StreamWriter writer; 
     try 
     { 
      writer = new StreamWriter(fileName); 
     } 
     catch 
     { 
      MessageBox.Show("Error, could not open " + fileName + " for saving"); 
     } 
     try 
     { 
      foreach (string entry in playerArray) 
      { 
       writer.WriteLine(entry); 
      } 
     } 
     catch 
     { 
      MessageBox.Show("Couldn't save"); 
     } 
     writer.Close();