Java异常

1. 异常

f9c2295872370bdd5356c76da575d302

2. Error和Exception

2694ca54c39dd2a402ad029604fd3951
b0ecc7ee5e5d4713e1c8e28e2afb4dd5

(1)Error

2925fa631756e3d6f9f3e166134d36bc

(2)Exception

d7da5eba0e3ddea1c875d6a490a00163

3. 异常处理机制:捕获和抛出异常

异常处理五个关键字:try、catch、finally、throw、throws

代码示例

package com.baidu.www;

public class test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        // try...catch...finally...
        /**
         * Ctrl + Alt + T键 快捷键生成语句
         */
        try{ // try 监控区域
            System.out.println(a/b);
        }catch (ArithmeticException e){ // catch 捕获异常
            System.out.println("出现异常!");
        }finally { // 处理善后工作
            /**
             * 假设I/O、资源,需要关闭!
             */
            System.out.println("嘻嘻!");
        }

        try {
            new test().a();
        }catch (StackOverflowError s){ // Throwable / Error / Exception /
            System.out.println("栈溢出异常!");
        }catch (Error e){
            System.out.println("错误!");
        }catch (Throwable t){
            System.out.println("异常!");
        }

        // throw
//        new test().test(1, 0);
        
        // throws
        try {
            new test().test(1, 0);
        } catch (ArithmeticException e) {
            throw new RuntimeException(e);
        }
    }

    public void a() {b();}
    public void b() {a();}

    // 假设方法中无法处理异常
    // 方法上抛出异常
    public void test(int a, int b) throws ArithmeticException{
        // 主动抛出异常
        // 一般在方法中使用
        if(b == 0){
            throw new ArithmeticException(); // 主动抛出一个异常
        }

        System.out.println(a/b);
    }
}

4. 自定义异常及经验

105c1cedba5ffa3a6762b87e94d4b7c1

代码示例

(1)MyException类

package com.baidu.www;

// 自定义异常类
public class MyException extends Exception{

    // 传递数字 > 10;
    private int detail;

    public MyException(int a){
        this.detail = a;
    }

    // toString:异常的打印信息

    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

(2)test类

package com.baidu.www;

public class test {

    // 可能会存在异常的方法

    static void test(int a) throws MyException{
        System.out.println("传递的参数为:" + a);

        if(a > 10){
            throw new MyException(a); // 抛出
        }
        System.out.println("OK!");
    }

    public static void main(String[] args) {
        try{
            test(1);
            test(78);
        }catch (MyException e){
            e.printStackTrace();
        }
    }
}

455eec728c033d442c1a330cb7fe0fc4

Alt + Enter快捷键

posted @ 2025-08-09 21:09  无敌美少女战士  阅读(5)  评论(0)    收藏  举报