2016-05-21 37 views
1

即時創建另一個方法,調用另一個類的方法。在嘗試捕獲後,netbeans一直告訴我「找不到符號:變量tLoad」,我做錯了什麼?試着抓錯

public Track trackLoader(String fileName) { 

    try { 
     Track tLoad = TrackReader.read(fileName); 


    } catch (IOException | FormatException ex) { 
     Logger.getLogger(RailwayModel.class.getName()).log(Level.SEVERE, null, ex); 
    } 

     return tLoad; 
    } 

回答

2

您必須聲明tLoadtry - 塊外面使用它的它之外。

public Track trackLoader(String fileName) { 
    Track tLoad = null; 
    try { 
     tLoad = TrackReader.read(fileName); 


    } catch (IOException | FormatException ex) { 
     Logger.getLogger(RailwayModel.class.getName()).log(Level.SEVERE, null, ex); 
    } 

     return tLoad; 
    } 
0

你的變量tLoad只生活在try塊,甚至不抓,絕對沒有經過他們。修正:

public Track trackLoader(String fileName) { 
     Track tLoad = null; 
     try { 
      tLoad = TrackReader.read(fileName); 
    } catch (IOException | FormatException ex) { 
     Logger.getLogger(RailwayModel.class.getName()).log(Level.SEVERE, null, ex); 
    } 

     return tLoad; 
    } 
0

JLS中解釋了這個很好:

局部變量聲明的塊中的範圍(§14.4)是在其中出現的聲明,從該塊的其餘部分它自己的初始化器,並在局部變量聲明語句右側包含任何其他聲明。 jls 6.3

甲的try-catch塊被定義爲:

TryStatement: 嘗試塊捕獲 try塊Catchesopt最後 TryWithResourcesStatement

jls 14.20

因此,在你的代碼

try { 
    Track tLoad = TrackReader.read(fileName); //<-- this variable 

    //is only visible until here 
} catch (IOException | FormatException ex) { 
    Logger.getLogger(RailwayModel.class.getName()).log(Level.SEVERE, null, ex); 
} 

    return tLoad; 
} 

由於tload纔可見,直到try-block結束,返回語句沒有任何意義。相反,你可以嘗試這樣的事情:

Track tLoad = null; 

try { 
    tLoad = TrackReader.read(fileName); 
} catch (IOException | FormatException ex) { 
    Logger.getLogger(RailwayModel.class.getName()).log(Level.SEVERE, null, ex); 
} 

    return tLoad; 
}