如何从Singleton java处理异常?

时间:2016-04-03 12:04:11

标签: java file exception singleton

我有一个单身课

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

如何将它重新抛出到主要位置并将其捕获? 主要课程

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

3 个答案:

答案 0 :(得分:1)

静态块仅在第一次加载类时执行,因此您可以使用下面的内容来重新抛出异常。在您的主要方法中,您将在(sshuttle) $ python setup.py --version 0.77 (sshuttle) $ cat >> setup.py # a comment (sshuttle) $ python setup.py --version 0.78.dev0+ng083293e.d20160403 块中围绕docs/conf.py调用,然后在getInstance()中,您可以执行您要查找的内容。

如果发生异常,则会在类加载时抛出并重新抛出此异常(从静态块中重新抛出)。 @Alexander Pogrebnyak所说的也是如此。

查看您提供的代码,因为您始终在阅读try-catch个文件,因此以下方法可行。如果你想要阅读不同的文件,然后重新抛出异常,那么这就变成了一个不同的故事,你没有问过那个部分,你所提供的代码也没有显示相同的部分。在任何情况下,如果您正在寻找的是:

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

PS:,因为静态块只在加载类时执行一次,并且每个JVM只加载一次类(直到你有自定义类加载器并覆盖行为)这样才能确保这个单例是线程安全的。

<强>代码:

catch

答案 1 :(得分: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,如果是多线程应用程序,则需要使用双重检查锁定synchronized新语句。在wiki中看到这个: https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java 享受..

答案 2 :(得分:0)

当您的单例静态初始化程序失败时,您将获得FileNameException

原因是它会有for gesture in view.gestureRecognizers! { if let recognizer = gesture as? UITapGestureRecognizer { view.removeGestureRecognizer(recognizer) } }

如果您没有做任何事情,默认异常处理程序会将整个堆栈跟踪打印为标准错误。