栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Java】异常

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Java】异常

文章目录
  • 异常的概念
  • 异常体系图
  • 常见的异常
  • 异常处理
  • 异常处理分类
  • 自定义异常
  • throw和throws的对比

异常的概念

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[] args) {
              int[] arrs = {1,2,3};
              System.out.println(arrs[3]);//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
          }
      }
      
      
  4. ClassCastException类型转换异常

    • public class ClassCastException_ {
          public static void main(String[] args) {
              A a = new A();
              B b = (B) a;//Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
          }
      }
      class A{
      
      }
      
      class B extends A{
      
      }
      
  5. NumberFormatException数字格式不正确异常

    • public class NumberFormatException_ {
          public static void main(String[] args) {
              String a = "123";
              int i = Integer.parseInt(a);
              System.out.println(i);//123
              
              String b = "嘻嘻";
              int i1 = Integer.parseInt(b);
              System.out.println(i1);//Exception in thread "main" java.lang.NumberFormatException: For input string: "嘻嘻"
          }
      }
      
      
异常处理

异常处理方式:

  1. try-catch-finally:在代码中捕获发生的异常,自行处理
  2. throws:将发生的异常抛出,交给调用者(方法)来处理,最顶级的处理者就是JVM

异常处理分类

try-catch-finally

  1. 如果异常发生了,异常发生后面的代码不执行,直接进入catch
  2. 没有发生异常,执行完try的语句,进入finally
  3. 不管发生不发生异常都进入finally
  4. 可以有多个catch,按子类异常在前,父类异常在后,发生异常时,只会匹配一个catch
public class Try_ {
    public static void main(String[] args) {
        System.out.println(T());
        // 3
        // 2
    }

    public static int T(){
        int a = 1;
        try {
            String[] s = new String[1];
            if (s[0].equals("1")){

            }
        } catch (Exception e) {
            return ++a;//2
        } finally {
            System.out.println(++a);//3
        }
        return ++a;
    }
}
public class Try_ {
   public static void main(String[] args) {
       System.out.println(T());
       // 3
   }

   public static int T(){
       int a = 1;
       try {
           String[] s = new String[1];
           if (s[0].equals("1")){

           }
       } catch (Exception e) {
           return ++a;//2
       } finally {
           return ++a;
       }
   }
}

throws异常处理

  1. 如果一个方法可能有异常,使用throws处理,则此方法显示声明抛出异常,表明该方法不对这些异常进行处理,而由该方法的调用者负责处理。
  2. 使用throws语句可以声明抛出异常的列表,可以是方法的异常或是父类。
  3. 子类重写父类方法时,抛出的异常和父类一致,或是父类抛出异常的子类。
  4. 运行异常,程序没有处理,默认就是throws方式。
  5. 编译异常,程序必须处理,比如try-catch或者throws。
import java.nio.file.FileAlreadyExistsException;

public class Throws_ {
    public static void f1() throws FileAlreadyExistsException {

    }

    public static void f2() throws FileAlreadyExistsException {
        f1();//编译异常需要也throws或者try
    }

    public static void f3() throws RuntimeException{

    }

    public static void f4() {
        f4();//运行异常不需要
    }

}
自定义异常

自定义继承Exception是编译异常,继承RuntimeException是运行异常。

public class ZiException {
    public static void main(String[] args) {
        int i = 2;
        if (i != 1){
            throw new IntException("不是1");//Exception in thread "main" IntException: 不是1
        }
        System.out.println("是1");
    }
}

class IntException extends RuntimeException{
    public IntException(String message) {//构造器
        super(message);
    }

}
public class ZiException {
    public static void main(String[] args) {

        try {
            Ex(2);
        } catch (IntException e) {
            System.out.println(e.getMessage());
        } finally {
        }

    }
    public static void Ex(int i){
        if (i != 1){
            throw new IntException("不是1");//Exception in thread "main" IntException: 不是1
        }
    }

}

class IntException extends RuntimeException{
    public IntException(String message) {//构造器
        super(message);
    }

}
throw和throws的对比
类型意义位置后面跟的东西
throws异常处理的方式方法声明处异常类型
throw手动生成异常对象的关键字方法体中异常对象
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/953071.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号