Java异常02:异常处理机制

本文详细介绍了Java中的异常处理机制,包括try、catch、finally等关键字的使用方法,并提供了具体的代码示例来展示如何捕获和处理异常。

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

异常处理机制

  • 抛出异常
  • 捕获异常

异常处理五个关键字

try、catch、finally、throw、throws

捕获异常


格式:

try {

        // 监控区,存放可能发生异常的代码

} catch (想要捕获的异常类型) {
        // 发生异常后需要执行的处理代码

} finally {

        // 可选项

        // 无论发不发生异常,都会执行的代码

}

使用例子:

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        
        // try 监控区
        // catch(想要捕获的异常类型) 捕获异常
        // finally 处理善后工作
        try {
            System.out.println(a/b);
        } catch(ArithmeticException e) {
            System.out.println("程序出现异常,变量b不能为0");
        } finally {
            System.out.println("finally");
        }
        
        // finally 可选项
        // 例如 IO 的操作,需要关闭资源。
    }
}

运行结果:

 

可以多个 catch 

注意:捕获的顺序从小到大,即上面异常的类型不能大于下面的异常类型,否则会提示异常已经被覆盖。

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        
        try {
            System.out.println(a/b);
        } catch(Error e) {
            System.out.println("Error");
        } catch(Exception e) {
            System.out.println("Exception");
        } catch(Throwable e) {
            System.out.println("Throwable");
        } finally {
            System.out.println("finally");
        }
        
    }
}

运行结果:

 

快速生成异常捕获代码

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
         
        // 选择下面这行可能会出现异常的代码
        // Ctrl + Alt + T
        // 然后选择 try/catch/finally
        // System.out.println(a/b);
        
       // 生成的代码如下:
       try {
           System.out.println(a/b);
       } catch (Exception e) {
           e.printStackTrace(); // 打印错误的栈信息
       } finally {}
    }
}

运行结果:

 

抛出异常


throw 方法内抛出异常

格式:

throw new 异常类()

一般在方法中使用,如果这个方法处理不了这个异常,方法上抛出异常。

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        
        if (b==0) { // throw
            throw new ArithmeticException();  // 主动抛出异常
        }
        System.out.println(a/b);
    }
}

throws 方法上抛出异常

格式:

throws 异常类

public class Test {
    public static void main(String[] args) {
       new Test().test(1,0);
    }
    
    public void test(int a, int b) throws ArithmeticException {
         if (b==0) { // throw
            throw new ArithmeticException();  // 主动抛出异常
         }
        System.out.println(a/b);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值