【Java】异常 try-catch throw 详解

异常的概念

Java语言中,将程序执行不正常的情况称为异常。

语法错误和逻辑错误不算。

异常分为两大类:

  1. Error错误,Java虚拟机无法解决的严重问题,程序会奔溃。JVM系统出错,资源耗尽,栈溢出等。
  2. Exception,其他因编程错误或偶然的外在因素导致的一般问题,可以使用针对性的代码进行处理。空指针访问,读不存在,网络终端等。Exception也分为两类:
    • 运行时异常,需要避免
    • 编译时异常,必须处理
      在这里插入图片描述

异常体系图

在这里插入图片描述

常见的异常

  1. NullPointerException空指针异常

    • public class NullPointerException_ {
             
          public static void main(String[] args) {
             
              String name = "hah";
              System.out.println(name.length());//3
              String sex = null;
              System.out.println(sex.length());//Exception in thread "main" java.lang.NullPointerException
          }
      }
      
  2. ArithmeticException数学运算异常

    • public class Exception01 {
             
          public static void main(String[] args) {
             
              //int i =  10/0;
              //System.out.println(i);
              // Exception in thread "main" java.lang.ArithmeticException: / by zero
              //at Exception01.main(Exception01.java:3)
      
              //使用try-catch异常处理机制
              //提高程序健壮性
              //进行异常处理,如果出现异常,程序会继续执行
              try {
             
                  int i = 10/0;
              } catch (Exception e) {
             
                  // e.printStackTrace();
                  System.out.println(e.getMessage());//输出异常信息 / by zero
              }
          }
      }
      
      
  3. ArrayIndexOutOfBoundsExceprion数组下标越界异常

    • public class ArrayIndexOutOfBoundsExceprion_ {
             
          public static void main(String
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

就爱喝菠萝啤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值