2016-04-03 64 views
1

我有一個單獨的類如何處理來自Singleton java的異常?

public class SingletonText { 
private static final CompositeText text = new CompositeText(new TextReader("text/text.txt").readFile()); 

public SingletonText() {} 
public static CompositeText getInstance() { 
    return text; 
}} 

而TextReader的構造函數會拋出異常FileNameEception

public TextReader(String filename) throws FileNameException{ 
    if(!filename.matches("[A-Za-z0-9]*\\.txt")) 
     throw new FileNameException("Wrong file name!"); 

    file = new File(filename); 
} 

我怎樣才能重新引發其主,並抓住它呢? 主類

public class TextRunner { 

public static void main(String[] args) { 
    // write your code here 
    SingletonText.getInstance().parse(); 

    System.out.println("Parsed text:\n"); 
    SingletonText.getInstance().print(); 

    System.out.println("\n\n(Var8)Task1:"); 
    SortWords.sortWords(SingletonText.getInstance().getText().toString(), "^[AEIOUaeiou].*", new FirstLetterComparator()); 
    System.out.println("\n\n(Var9)Task2:"); 
    SortWords.sortWords(SingletonText.getInstance().getText().toString(), "^[A-Za-z].*", new LetterColComparator()); 
    System.out.println("\n\n(Var16)Task3:"); 
    String result = SubStringReplace.replace(SingletonText.getInstance() 
      .searchSentence(".*IfElseDemo.*"), 3, "EPAM"); 
    System.out.println(result); 
}} 

回答

0

嘗試懶惰初始化單例。 是這樣的:

public class SingletonText { 
private static CompositeText text; 

public SingletonText() { 
} 

public static CompositeText getInstance() { 
    if (text ==null) { 
     text = new CompositeText(new TextReader("text/text.txt").readFile()); 
    } 
    return text; 
} 
} 

此外,您還需要聲明構造private,如果多線程應用程序,你需要​​具有雙重檢查鎖定新的聲明。在wiki中看到: https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java 享受..

+0

胡斯塔小的修正:變量不能在這種方法'final'。 – dambros

+0

你說得對。修復。 – chico

+0

不要這樣做。 SingletongText不再是線程安全的。 –

0

當你的singleton靜態初始化器失敗時,你會得到java.lang.ExceptionInInitializerError

作爲一個原因,它將有你的FileNameException

如果你什麼也沒做,默認異常處理程序會將整個堆棧跟蹤打印到標準錯誤。

1

只有在第一次加載類時纔會執行靜態塊,因此您可以使用下面的代碼來重新拋出異常。在你的主要方法中,你將在try-catch塊中圍繞getInstance()調用,然後在catch中,你可以做任何你正在尋找的東西。

在發生異常的情況下,這個異常將在類加載時拋出並重新拋出(來自您的靜態塊)一次。亞歷山大·波格雷布尼亞克所說的也是如此。

看看你提供的代碼,因爲你總是閱讀text/text.txt文件,所以下面的方法將起作用。如果你正在閱讀不同的文件,然後重新拋出異常,那麼這將成爲一個不同的故事,並且你沒有問過那個部分,你提供的代碼也沒有顯示相同的內容。無論如何,如果這就是你正在尋找的那麼:

  • 你需要創建一個你的CompositeText類的單例對象。
  • 創建setter方法將創建一個對象TextReader類使用傳遞的文件名字符串。
  • 該setter方法將有try-catch塊,並在catch塊中,您將重新拋出異常,以便您可以在main方法中再次捕獲。

PS:因爲靜態塊被執行時僅加載類和類每個JVM只加載一次(除非您有自定義類加載器和重寫行爲)一度讓這確保了此單是thread-安全。

代碼:

public class SingletonText {  
    private static CompositeText text = null; 

    static{ 
     try { 
      text = new CompositeText(new TextReader("text/text.txt").readFile()); 
     } catch (FileNameException e) { 
      // TODO: re-throw whatever you want 
     } 
    } 
    public SingletonText() {} 
    public static CompositeText getInstance() { 
     return text; 
    } 
}