Java Exception和Error的差别
Java中异常的抽象类是Throwable,在此基础上。派生出两大类:Error和Exception。
Error是程序中的严重错误,不应该用try…catch包括。Javadoc的说明例如以下:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
常见的Error有:AssertionError、OutOfMemoryError、StackOverflowError。
Exception分两类:Checked Exception和Unchecked Exception。
Unchecked Exception的基类是RuntimeException。全部继承自RuntimeException的Exception都属于Unchecked Exception, 如:NullPointerException、ArrayIndexOutOfBoundsException。
Checked Exception直接继承自Exception,全部不继承RuntimeException的Exception都属于Checked Exception,如:FileNotFoundException。
Checked Exception和Unchecked Exception都能够用try…catch包括。当中,Checked Exception在编译时检查是否有想要的catch处理,因此必要有try…catch包括,或者方法签名处抛出相应的异常。而Unchecked Exception在运行时推断,所以不一定要try…catch包括。并且,Unchecked Exception往往是程序本身存在bug,一般不catch这种错误。
备注1:
在try中运行return语句,依旧会运行finally语句块。除非在try语句中结束JVM进程(system.exit(0))
public class Hello{
public static void main(String[] args){
try{
System.out.println("in try");
return;
}catch(Exception e){
}finally{
System.out.println("finally");
}
System.out.println("end");
}
}
//输出
in try
finally
备注2:
不要在finally语句块调用return。否则的话。在try语句块中抛出的异常无法被调用者捕获,例如以下:
try {
doSomething();
System.out.println("No Exception Caught!");
} catch (RuntimeException e) {
System.out.println("got it.");
}
}
public static void doSomething() {
try {
throw new RuntimeException();
} finally {
return;
}
}
//输出
No Exception Caught!
备注3:
throw与throws的差别:
throw是在语句块。程序猿主动抛出一个异常。
throws是在方法的签名处,说明该方法可能抛出的异常。当有多个异常抛出时,用逗号分隔。
备注4:
从JDK7開始,同一个try相应的多个catch能够写在一起。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
· AI Agent爆火后,MCP协议为什么如此重要!