java - 如果抛出异常,finally 块不会执行
问题描述
如果在 try 块中抛出异常,finally 块将执行:
public class ExceptionTest{
public static void main(String args[])
{
System.out.println(print());
}
public static int print()
{
try
{
throw new NullPointerException();
}
finally
{
System.out.println("Executing finally block");
}
}
}
输出:
Executing finally block
Exception in thread "main" java.lang.NullPointerException
at ExceptionTest.print(ExceptionTest.java:11)
at ExceptionTest.main(ExceptionTest.java:4)
另一方面, finally 不会在此代码中被调用:
public class ExceptionTest{
public static void main(String args[])
{
System.out.println(print());
}
public static int print()
{
try
{
throw new Exception();
}
finally
{
System.out.println("Executing finally block");
}
}
}
输出:
ExceptionTest.java:11: error: unreported exception Exception; must be caught or declared to be thrown
throw new Exception();
^
1 error
为什么 NullPointerException 类很酷,但在 Exception 类时却抱怨?
解决方案
NullPointerException 是未经检查的异常。检查本指南。
这是一个捕获所有内容的 try and catch 块的示例:
try {
//Do Something
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
finally {
System.out.println("The 'try catch' is finished.");
}
推荐阅读
- php - SELECT SUM 内循环
- php - 如何更改在 Symfony 中导入的 parameters.php 中的 parameters.yml 中设置的参数
- r - 使用自定义统计在 R 中使用汇总函数时出错
- c++ - InterlockedCompareExchange64 + Read32 操作组合的有效性
- google-calendar-api - “超出堆栈限制”是什么意思?
- microsoft-graph-api - 图 API 认证 | 请求正文必须包含以下参数“grant_type”
- reactjs - 延迟 @loadable/component 的加载
- javascript - 意外的令牌,预期的“...”反应原生
- autohotkey - 用于更改 RButton 行为的 AHK 脚本
- google-apps-script - Google 表格查询重复的第一行 + 结果错误