首页 > 解决方案 > 在main方法中抛出异常后如何处理?

问题描述

是否有任何更高的方法可以捕获和处理main方法中发生的异常?

我们该如何应对?

这是Java编程简介(第12章)给出的一个例子

//Listing 12.13 WriteData.java
class WriteData {
 public static void main(String[] args) **throws IOException** {
    java.io.File file = new java.io.File("scores.txt");
    if (file.exists()) {
      System.out.println("File already exists");
      System.exit(1);
    }

    // Create a file
    java.io.PrintWriter output = new java.io.PrintWriter(file);

    // Write formatted output to the file
    output.print("John T Smith ");
    output.println(90);
    output.print("Eric K Jones ");
    output.println(85);

    // Close the file
    output.close();
  }
}

标签: javaexception

解决方案


每当任何线程抛出未在其调用堆栈中的任何位置处理的异常时,都会调用(请参阅)UncaughtExceptionHandler上的存在。这不仅适用于默认线程,还适用于手动创建的每个线程。默认情况下,线程没有.ThreadThread.setUncaughtExceptionHandlermainmainUncaughtExceptionHandler

如果Thread没有,则ThreadGroup处理它,如ThreadGroup.uncaughtException.

这演示了一个简单的异常处理程序的样子:

class ExceptionHandlerSample {
  public static void main(String[] args) {
    Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
    ((Object) null).toString(); // force a NullPointerException to be thrown.
  }
}

class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
  @Override
  public void uncaughtException(Thread t, Throwable e) {
    System.out.printf("Thread %s threw an exception of type %s: %s",
        t.getName(), e.getClass().getSimpleName(), e.getMessage());
  }
}

推荐阅读