如何使用Java异常处理

发布时间:2020-08-04 09:17:14 作者:小猪
来源:亿速云 阅读:101

这篇文章主要为大家展示了如何使用Java异常处理,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

异常:

常见异常:

算术异常类:ArithmeticExecption

空指针异常类:NullPointerException

类型强制转换异常:ClassCastException

数组下标越界异常:ArrayIndexOutOfBoundsException

输入输出异常:IOException


处理异常:

如何使用Java异常处理

如何使用Java异常处理

public class Demo {

  public static void main(String[] args) {
//    int a=10/0;
    try{
      int a=10/0;
    }catch(ArithmeticException e) {
      System.out.println("run in ArithmeticException "+e);
      //run in ArithmeticException java.lang.ArithmeticException: / by zero
    }
    catch (Exception e) {
      System.out.println(e);
    }finally {
      System.out.println("最终执行的");//最终执行的
    }

  }

}

throws用于声明异常,声明函数可能发生的异常。【当函数中有throw来抛出异常时,函数头必须使用throws声明异常】

throw用于手动抛出异常,可以抛出自定义异常信息:throw 异常类型(异常信息)

public class Demo2 {
  
  static int div(int a,int b) throws ArithmeticException{
    if (b==0){
      throw new ArithmeticException("发生除零异常了!");
    }
    return a/b;
  }
  
  public static void main(String args[]) {
    try {
      System.out.println(div(2,0));
    }catch(ArithmeticException e) {
      System.out.println(e.getMessage());//发生除零异常了!
    }finally {
      System.out.println("in finally");//in finally
    }
    System.out.println("after finally");//after finally
    
  }
}

一般对于不想在函数中处理异常时,一般采用异常抛出处理(throw throws);否则使用try…catch…finally捕获异常。

自定义异常:

有时候没有定义我们想要的异常(比如我们MYSQL连接异常),那么我们可以自定义异常。

class MyException extends Exception{
  public MyException() {}
  public MyException(String msg) {
    super(msg);
  }
}

public class Demo3 {
  
  static int div(int a,int b) throws MyException {
    if (b==0){
      throw new MyException("发生异常了!");
    }
    return a/b;
  }
  
  public static void main(String args[]) {
    try {
      System.out.println(div(2,0));
    }catch(Exception e) {
      System.out.println(e);//异常.MyException: 发生除零异常了!
    }
    
  }
}

断言:

public class Demo {

  public static void main(String[] args) {
    Boolean food=false;
    System.out.println("准备开始吃饭");
    assert food;
    
    System.out.println("饭来了");
    

  }

}

如何使用Java异常处理

以上就是关于如何使用Java异常处理的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

推荐阅读:
  1. java异常处理机制是什么
  2. Java异常处理操作实例小结

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java ava

上一篇: Oracle bigfile 大文件表空间

下一篇:Redis Cluster集群数据分片机制是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》