异常类继承
checked && unchecked
- checked—-编译期间
- 必须显式进行捕获处理
- unchecked—-运行时
- 运行时异常,譬如NullpointerException, ArrayIndexOutOfBoundException
异常处理
catch 不是必须的
- try/catch/finally语法中,catch不是必需的,也就是可以只有try/finally,表示不捕获异常,异常自动向上传递,但finally中的代码在异常发生后也执行
Returning from inside a
finally
block will causeexceptions
to be lost.不要在finally写return
/**
* Returning from inside a finally block will cause exceptions to be lost.
* 不会抛出异常
* 会直接返回10
*/
private fun throwFinally(): Int {
try {
return 1
throw RuntimeException("testing")
} catch (e: Exception) {
e.printStackTrace()
} finally {
return 10
}
}
/**
* Returning from inside a finally block will cause exceptions to be lost.
* 不会抛出异常
* 会直接返回10
*/
private fun throwFinally1(): Int {
try {
return 1
throw RuntimeException("testing")
} finally {
return 10
}
}
return vs finally
其实return与finally并没有明显的谁强谁弱。在执行时,是return语句先把返回值写入但内存中,然后停下来等待finally语句块执行完,return再执行后面的一段
return语句返回的是一个值,
- 当这个值是基本类型时,在后续finally修改也不会改变
当这个值是引用类型时,在后续finally修改,值肯定改变 ```java //返回基本类型,该函数返回的是10
public int fun() { int i = 10; try {//doing something
return i;
}catch(Exception e){
return i;
}finally{
i = 20;
} }
//返回HelloWordFinally,因为返回的引用 public StringBuilder fun() { StringBuilder s = new StringBuilder(“Hello”); try {
//doing something
s.append("Word");
return s;
}catch(Exception e){
return s;
}finally{
string.append("finally");
} } ```