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

问题

Exception 和 Error 有什么区别?运行时异常与一般异常有什么区别?

解析

Exception 和 Error 都继承了 Throwable 类。只有 Throwable 的可以被 throw 和 catch。Exception 是程序正常情况下可以预料的,Error 通常会导致程序不可恢复。Exception 分为可检查异常和不检查异常,不检查异常就是运行时异常。

NoClassDefFoundError 和 ClassNotFoundException 区别

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

异常处理的基本原则

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

例如:

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

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

猜你喜欢

转载自juejin.im/post/5dbbcd30f265da4d1b51cf54