2014-01-17 18 views
-2

我對Java很新,所以如果這是一個愚蠢的問題,請道歉。使用異常時變量無法訪問

我有以下功能

public static List<String[]> read(String document) throws IOException{ 
     try{ 
      CSVReader reader = new CSVReader(new FileReader(document)); 
      List<String[]> data = reader.readAll(); 
      reader.close(); 
     } catch(IOException e){ 
      e.printStackTrace(); 
     } 
     return data; 
    } 

但是我收到一個錯誤,數據不能被解析爲一個變量。但是,如果我,但在try語句返回錯誤消失,並指出該函數應返回。由於變量是在函數內部,我會認爲,不管捕獲它是否允許這樣做。任何人都可以向我解釋我哪裏錯了嗎?

+1

聲明「列表數據;」在try語句之外。 – reblace

+0

您正嘗試訪問聲明它的塊之外的數據。將聲明移出try塊。 – kmera

+0

不,您的數據是在try內部聲明的。另外,read()中沒有其他名爲data的變量。所以你得到那個沒有解決的錯誤。 – Steam

回答

4

這很簡單。問題是「數據」只存在於「try」塊的範圍內。除此之外,它是不確定的。一個簡單的解決方案可能是這樣的:

public static List<String[]> read(String document) throws IOException{ 

     List<String[]> data = null; 
     try{ 
      CSVReader reader = new CSVReader(new FileReader(document)); 
      data = reader.readAll(); 
      reader.close(); 
     } catch(IOException e){ 
      e.printStackTrace(); 
     } 
     return data; 
    } 
+0

謝謝你的回答。我已投票選出要關閉的職位,但如果我可以在職位關閉前將我的答案標記爲正確。我並不知道try塊被歸類爲範圍,但感謝您的幫助。 –

+0

在失敗的情況下,'= null'實際上非常重要! – BrainStone

0

數據範圍位於try子句的大括號之間,因此您無法在該範圍外訪問它。您需要在嘗試之外定義數據以將其返回到try之外。

1

您需要聲明變量的數據在同一塊

public static List<String[]> read(String document) throws IOException{ 
    List<String[]> data; 
    try{ 
     CSVReader reader = new CSVReader(new FileReader(document)); 
     data = reader.readAll(); 
     reader.close(); 
    } catch(IOException e){ 
     e.printStackTrace(); 
    } 
    return data; 
} 
1
public static List<String[]> read(String document) throws IOException{ 
    List<String[]> data = null; //Declare your variable here 
    try{ 
     CSVReader reader = new CSVReader(new FileReader(document)); 
     data = reader.readAll(); //Initialize your variable here 
     reader.close(); 
    } catch(IOException e){ 
     e.printStackTrace(); 
    } 
    return data; 
} 

聲明你的try塊以外的變量。當你這樣做時,它將在該try塊之外被訪問,例如,你的return語句在哪裏。

1

很簡單的問題的答案將是:

public static List<String[]> read(String document) throws IOException{ 
    List<String[]> data = null; 

    try{ 
     CSVReader reader = new CSVReader(new FileReader(document)); 
     data = reader.readAll(); 
     reader.close(); 
    } catch(IOException e){ 
     e.printStackTrace(); 
    } 

    return data; 
} 

這是因爲data被宣佈try catch塊或作爲它也被稱爲範圍(我會堅持到塊)。在塊中聲明的所有內容只能在該塊內部或內部塊中加以說明。

另一個解決方案如下。它避免了聲明(和initialzing)data變量,如果沒有neccessary:

public static List<String[]> read(String document) throws IOException{ 
    try{ 
     CSVReader reader = new CSVReader(new FileReader(document)); 
     List<String[]> data = reader.readAll(); 
     reader.close(); 

     // Return early. Note this only happens when everything went right. 
     // (Which is what we hope for) 
     return data; 
    } catch(IOException e){ 
     e.printStackTrace(); 
    } 

    // This will only happen when it caught a exception! 
    return null; 
} 

但是我會堅持到第一個解決方案!

+0

+1瞭解更多信息。謝謝您的意見。 –