异常

本文详细介绍了Java中的异常处理机制,包括异常的分类、捕获、抛出及自定义异常等内容。通过具体示例展示了如何使用try...catch...finally结构来处理程序运行时可能出现的异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常


1. 异常的概述

异常就是在程序运行时出现的意外错误称为“异常”。在Java中异常分为两类:

  1. 错误(Error):一般是指与虚拟机相关的问题,如系统崩溃、虚拟机错误、动态链接失败等,这些错误无法恢复或捕获,将导致应用程序中断;

  2. 异常(Exception):因程序编码错误或外在因素导致的问题,这些问题能够被系统捕获并进行处理,从而避免应用程序非正常中断,例如:除数为0、对负数开平方、空指针访问等;

Java中的异常类:

Exception异常又分为一下两种类型:

  1. 运行时异常(RunTimeException及其所有子类):在编译时可以被忽略,不要求强制处理,这种异常是编码或设计不得当导致的,这种异常是可以避免的。

  2. 检查性异常(除RunTimeException及其子类外):在编译时不可以被忽略,必须做出处理的异常,否则程序编译不通过。这种异常是程序在运行时因外界因素导致的,而且是可以预知的。

2. 捕获异常

使用try…catch捕获异常:

单catch:
public class Test {

    public static void main(String[] args) {
        int a = 10, b = 0;

        try {
            System.out.println("Programme start....");
            System.out.println(a / b);//发生异常,中止try语句块,直接跳到catch语句块
        } catch (Exception e) {
            System.out.println("Programe Exception");
            e.printStackTrace();//异常处理
        }
        System.out.println("Programe end.....");

    }
}

多catch:
public class Test {

    public static void main(String[] args) {
        int a = 10, b = 0;
        try {
            System.out.println("Programe start....");
            System.out.println(a / b);
        } catch (NullPointerException e) {
            System.out.println("Programe NullPointerException");
            e.printStackTrace();
        } catch (ArithmeticException e) {
            System.out.println("Programe ArithmeticException...");
            e.printStackTrace();
        }
         System.out.println("Programe end.....");

    }
}

try...catch...finlly:

public class Test {

    public static void main(String[] args) {
        FileInputStream fileInputStream = null;//io流都需要关闭,否则会占用资源
        try {

            System.out.println("Programe start....");
            fileInputStream = new FileInputStream("/a.text");

        } catch (FileNotFoundException e) {
            System.out.println("Programe file not found Exception");//发生异常
            e.printStackTrace();
        } finally {
            /**
             * 不管前面是执行了try语句块,还是catch语句块,甚至在这两个语句块中有return
             * 执行完后都将执行此处的语句块,所以 finally 通常是用来放回收代码的
             * 
             * Java垃圾回收机制不会回收任何物理资源,
             * 垃圾回收机制只能回收堆内存中对象所占用的内存,回收物理资源
             * 在Java中,通常用finally回收物理资源
             * */

            try {
                System.out.println("Closs File Input Stream!...");
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Programe end.....");

    }
}

try语句:
public class Test {

    public static void main(String[] args) {
        /**
         * 这种写法是用来释放资源的
         * 尽管这里没有写关闭输入流
         * Java会自动关闭输入流的
         * */
        try(FileInputStream fileInputStream = new FileInputStream("/a.text")) {

            System.out.println("Programe start....");

        } catch (IOException e) {
            System.out.println("Programe file not found Exception");//发生异常
            e.printStackTrace();
        }
        System.out.println("Programe end.....");

    }
}

3. 抛出异常

throw抛出异常:
public class Test {

    public static void main(String[] args) {
        exception();
    }

    public static void exception() {
        int a = 10, b = 0;
        try {
            System.out.println("Programme start....");
            if (b == 0) {
                //将异常抛出,直接跳到catch语句块
                throw new Exception("除数不能为0");//抛出异常实例对象
            }
            System.out.println("......");
            System.out.println(a / b);

        } catch (Exception e) {
            System.out.println("progame exception...");
            e.printStackTrace();
        }

        System.out.println("Programe end.....");
    }
}

throws抛出异常:

public class Test {

    public static void main(String[] args) {
        try {
            exception();//完成该方法的异常处理
        } catch (Exception e) {
            System.out.println("find a exception");
            e.printStackTrace();
        }

    }

    //throws 可以抛出异常序列   
    public static void exception() throws Exception {
        int a = 10, b = 0;

        System.out.println("Programme start....");

        System.out.println(a / b);

        System.out.println("Programe end.....");
    }
}

4. 自定义异常

public class MyException extends Exception {

    public MyException() {
    }

    public MyException(String msg) {
        super(msg);
    }
}


public class Test {

    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(System.in);

            System.out.println("请输入一个数");

            int a = scanner.nextInt();

            if (a > 100) {

                throw new MyException("输入的数大于100");

            }

        } catch (MyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值