Java 在main方法中抛出异常后如何处理它们?
是否有更高级的方法可以捕获和处理主方法中发生的异常 我们怎么处理呢 下面是第12章Java编程简介中给出的一个示例Java 在main方法中抛出异常后如何处理它们?,java,exception,Java,Exception,是否有更高级的方法可以捕获和处理主方法中发生的异常 我们怎么处理呢 下面是第12章Java编程简介中给出的一个示例 //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())
//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();
}
}
每当任何线程抛出其调用堆栈中任何位置都未处理的异常时,就会调用线程see上存在的UncaughtExceptionHandler。这不仅适用于默认主线程,也适用于手动创建的每个主线程。默认情况下,主线程没有UncaughtExceptionHandler
如果线程没有线程,那么线程组将处理它,如中所述
这演示了简单异常处理程序的外观:
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());
}
}
您可以在捕获异常和使用try{}catch{}语句在同一方法中处理异常之间进行选择,或者像示例一样抛出异常,然后在其他方法中捕获它。