异常类继承

image.png

checked && unchecked

  • checked—-编译期间
    • 必须显式进行捕获处理
  • unchecked—-运行时
    • 运行时异常,譬如NullpointerException, ArrayIndexOutOfBoundException

异常处理

catch 不是必须的

  • try/catch/finally语法中,catch不是必需的,也就是可以只有try/finally,表示不捕获异常,异常自动向上传递,但finally中的代码在异常发生后也执行
  • Returning from inside a finally block will cause exceptions to be lost.

    • 不要在finally写return

      1. /**
      2. * Returning from inside a finally block will cause exceptions to be lost.
      3. * 不会抛出异常
      4. * 会直接返回10
      5. */
      6. private fun throwFinally(): Int {
      7. try {
      8. return 1
      9. throw RuntimeException("testing")
      10. } catch (e: Exception) {
      11. e.printStackTrace()
      12. } finally {
      13. return 10
      14. }
      15. }
      16. /**
      17. * Returning from inside a finally block will cause exceptions to be lost.
      18. * 不会抛出异常
      19. * 会直接返回10
      20. */
      21. private fun throwFinally1(): Int {
      22. try {
      23. return 1
      24. throw RuntimeException("testing")
      25. } finally {
      26. return 10
      27. }
      28. }

return vs finally

其实return与finally并没有明显的谁强谁弱。在执行时,是return语句先把返回值写入但内存中,然后停下来等待finally语句块执行完,return再执行后面的一段

  • return语句返回的是一个值,

    • 当这个值是基本类型时,在后续finally修改也不会改变
    • 当这个值是引用类型时,在后续finally修改,值肯定改变 ```java //返回基本类型,该函数返回的是10
      public int fun() { int i = 10; try {

      1. //doing something
      2. return i;

      }catch(Exception e){

      1. return i;

      }finally{

      1. i = 20;

      } }

    //返回HelloWordFinally,因为返回的引用 public StringBuilder fun() { StringBuilder s = new StringBuilder(“Hello”); try {

    1. //doing something
    2. s.append("Word");
    3. return s;

    }catch(Exception e){

    1. return s;

    }finally{

    1. string.append("finally");

    } } ```