Java 核心 Exception 和 Error 有什么区别?

问题

Exception 和 Error 有什么区别?运行时异常与通常异常有什么区别?java

解析

Exception 和 Error 都继承了 Throwable 类。只有 Throwable 的能够被 throw 和 catch。Exception 是程序正常状况下能够预料的,Error 一般会致使程序不可恢复。Exception 分为可检查异常和不检查异常,不检查异常就是运行时异常。ui

NoClassDefFoundError 和 ClassNotFoundException 区别

NoClassDefFoundError 一般发生在打包错误致使编译时找获得包而运行时找不到包致使的项目不能启动的错误,ClassNotFoundException 发生在好比用 Class.fromName() 加载一个不存在的包致使的 Exception。spa

异常处理的基本原则

  1. 捕获特定异常
  2. 不要 swallow 异常

例如:code

try {
 // 业务代码
 // …
 Thread.sleep(1000L);
} catch (Exception e) {
 // Ignore it
}
复制代码

Throw early, catch late 原则

  1. throw early
public void readPreferences(String fileName){
	 //...perform operations... 
	InputStream in = new FileInputStream(fileName);
	 //...read the preferences file...
}

public void readPreferences(String filename) {
	Objects. requireNonNull(filename);
	//...perform other operations... 
	InputStream in = new FileInputStream(filename);
	 //...read the preferences file...
}
复制代码
  1. catch late

可考虑使用自定义异常,方便定位,同时注意不要暴漏敏感信息。如用户信息不容许输出。orm


每一次成长,都想与你分享。 cdn

相关文章
相关标签/搜索