簡體   English   中英

如何處理來自單例 java 的異常?

[英]How to handle Exception from 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;
}}

以及可以拋出 FileNameEception 的 TextReader 構造函數

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

    file = new File(filename);
}

我怎樣才能將它重新拋出到 main 並在那里捕獲它? 主班

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);
}}

靜態塊僅在第一次加載類時執行,因此您可以使用以下內容來重新拋出異常。 在您的 main 方法中,您將在try-catch塊中包圍getInstance()調用,然后在catch您可以執行任何您想要的操作。

在異常的情況下,這個異常將在類加載時被拋出並重新拋出(來自你的靜態塊)。 @Alexander Pogrebnyak 所說的也是真的。

查看您提供的代碼,因為您總是在閱讀text/text.txt文件,因此以下方法將起作用。 如果您希望讀取不同的文件然后重新拋出異常,那么這一切就變成了一個不同的故事,而且您沒有問過那部分,您提供的代碼也沒有顯示相同的內容。 無論如何,如果這就是您要找的東西,那么:

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

PS:由於靜態塊僅在加載類時執行一次,並且每個 JVM 只加載一次類(直到您擁有自定義類加載器並覆蓋行為),因此這可確保此單例是線程安全的。

代碼:

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;
    }
}

嘗試延遲初始化單例。 像這樣:

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 ,如果它是多線程應用程序,則需要使用雙重檢查鎖定synchronized新語句。 在 wiki 中看到這個: https : //en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java享受..

當您的單例靜態初始化程序失敗時,您將收到java.lang.ExceptionInInitializerError

作為一個原因,它會有你的FileNameException

如果您什么都不做,默認異常處理程序會將整個堆棧跟蹤打印到標准錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM