java - 在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();
}
}
解决方案
每当任何线程抛出未在其调用堆栈中的任何位置处理的异常时,都会调用(请参阅)UncaughtExceptionHandler
上的存在。这不仅适用于默认线程,还适用于手动创建的每个线程。默认情况下,线程没有.Thread
Thread.setUncaughtExceptionHandler
main
main
UncaughtExceptionHandler
如果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());
}
}
推荐阅读
- c# - 如何访问 C# 项目目录
- python - 当我运行我的 python 文本游戏时,我得到一个属性错误,我不知道如何解决
- javascript - 样式导入自定义组件
- node.js - 如何使用节点获取请求设置参数
- c++ - Cuda 错误越界
- r - R Highcharter:格式化双 y 轴图表
- spring-boot - 为什么我需要为 JdbcTemplate 指定架构
- javascript - (ReactJS)即使数据库已更新,页面上的项目列表也不会更新
- javascript - 在 Android 上的 Chrome 上创建始终位于最前面的通知
- r - 如何在 R 中将“字符”类转换为“数字”类