Java基础异常处理代码及原理解析
更新:HHH   时间:2023-1-8


这篇文章主要介绍了java基础异常处理代码及原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

异常的定义:中断了正常指令流的事件。

try..catch..finally结构:

class Test{
  public static void main(String[] args){
    System.out.println(1);
    try{
      System.out.println(2);
      int i = 1 / 0;
      System.out.println(3);
    }
    catch(Exception e){
      e.printStackTrace();
      System.out.println(4);
    }
    finally{
      System.out.println(5);
    }
    System.out.println(6);
  }
}

输出结果:

  D:\Java\code\练习十二>java Test
java.lang.ArithmeticException: / by zero
    at Test.main(Test.java:6)

throw与throws关键字

class User{
  private int age;
  public void setAge(int age) throws Exception{
    if(age <= 0){
      Exception e = new Exception("input age is error!");
      throw e;
    }
    else{
      this.age=age;
    }
     
  }
}
class Test{
  public static void main(String[] args){
    User u = new User();
    try{
      u.setAge(-20);
    }
    catch(Exception e){
      System.out.println(e);
    }
    
  }
}
D:\Java\code\练习十二>java Test
java.lang.Exception: input age is error!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持天达云。

返回编程语言教程...