【问题标题】:How to handle Exception from Singleton java?如何处理来自 Singleton java 的异常?
【发布时间】:2016-04-03 12:04:11
【问题描述】:

我有一个单例类

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

【问题讨论】:

    标签: java file exception singleton


    【解决方案1】:

    静态块仅在第一次加载类时执行,因此您可以使用以下内容来重新抛出异常。在你的 main 方法中,你将在 try-catch 块中包围 getInstance() 调用,然后在 catch 中你可以做任何你想做的事情。

    如果出现异常,这个异常只会在类加载时被抛出并重新抛出(从你的静态块中)一次。 @Alexander Pogrebnyak 所说的也是正确的。

    查看您提供的代码,因为您一直在阅读text/text.txt 文件,所以下面的方法将起作用。如果您希望读取不同的文件,然后重新抛出异常,那么这将成为一个不同的故事,并且您没有询问该部分,您提供的代码也没有显示相同的内容。无论如何,如果这就是您要寻找的,那么:

    • 您需要创建CompositeText 类的单例对象。
    • 创建一个setter方法将使用传递的文件名字符串创建一个对象TextReader类。
    • 该 setter 方法将具有 try-catch 块,并且在 catch 块中您将重新抛出异常,以便您可以在 main 方法中再次捕获。

    P.S.: 因为静态块在加载类时只执行一次,并且每个 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;
        }
    }
    

    【讨论】:

      【解决方案2】:

      尝试延迟初始化单例。 像这样:

      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 带有双重检查锁定的新语句。在维基中看到这个: https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java 享受..

      【讨论】:

      • 小修正:在这种方法中变量不能是final
      • 这就是为什么我将链接添加到 wiki,如果他在多线程应用程序中需要它。
      • 试过了,但我只是失去了对象的价值......我不需要多线程应用程序
      • 这是我在 TextReader 中的错误!现在一切正常。谢谢
      【解决方案3】:

      当您的单例静态初始化程序失败时,您将获得 java.lang.ExceptionInInitializerError

      因此它会有你的FileNameException

      如果您什么都不做,默认的异常处理程序会将整个堆栈跟踪打印到标准错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-15
        • 2010-12-09
        • 2011-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多