Thinking in java Exception

本文提供了五个Java异常处理的练习示例,包括基本的异常抛出与捕获、自定义异常类及异常堆栈跟踪的使用等。通过这些练习,读者可以加深对Java异常处理机制的理解。

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

课后习题:

exercise1:

package Exception;

public class Exercise1 {

    public static void main(String[] args) {
    try {
        throw new Exception("abc");
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        System.out.println("执行了");
    }
    }

}

exercise2:


public class Exercise2 {
    void f() {

    }
    public static void main(String[] args) {
    Exercise2 e2 = null;
    try {
        e2.f();
    } catch (Exception e) {
        e.printStackTrace();
    }


    }

}

exercise3:

package Exception;

public class Exercise3 {

    public static void main(String[] args) {
    try {
        throw new ArrayIndexOutOfBoundsException();
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    }

    }

}

exercise4:

package Exception;

public class MyException extends Exception{
    String s;
    public MyException(String s) {
        this.s =s;
    }
    void print() {
        System.out.println(s);
    }
    public static void main(String[] args) {
    try {
        throw new MyException("abc");
    } catch (MyException e) {
        e.print();
        e.printStackTrace();
    }

    }

}

exercise5:

来自原书文档。

public class Ex5 {
    private static int[] ia = new int[2];
    static int x = 5;   
    public static void main(String[] args) {
        while(true) {
            try {
                ia[x] = 1;
                System.out.println(ia[x]);
                break;  
            } catch(ArrayIndexOutOfBoundsException e) {
                System.err.println(
                    "Caught ArrayIndexOutOfBoundsException");
                    e.printStackTrace();
                x--;
            } finally {
                System.out.println("Are we done yet?");     
            }
        }
        System.out.println("Now, we're done.");
    }   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值