10.19

发布时间 2023-11-07 16:11:34作者: new菜鸟

动手动脑

运行示例并了解Java中实现异常处理的基础知识

Java提供了一套异常处理机制,通过使用try-catch-finally语句块来捕获和处理异常。try语句块包含可能发生异常的代码,catch语句块用于捕获特定类型的异常并进行处理,finally语句块用于无论是否发生异常都要执行的代码,例如释放资源等。try-catch-finally语句块可以嵌套使用,也可以在方法声明中使用throws关键字来抛出异常,让调用者来处理。

 

复制代码
package kaoshichengji;
public class CatchWho { 
    public static void main(String[] args) { 
        try { 
                try { 
                    throw new ArrayIndexOutOfBoundsException(); 
                } 
                catch(ArrayIndexOutOfBoundsException e) { 
                       System.out.println(  "ArrayIndexOutOfBoundsException" +  "/内层try-catch"); 
                }
 
            throw new ArithmeticException(); 
        } 
        catch(ArithmeticException e) { 
            System.out.println("发生ArithmeticException"); 
        } 
        catch(ArrayIndexOutOfBoundsException e) { 
           System.out.println(  "ArrayIndexOutOfBoundsException" + "/外层try-catch"); 
        } 
    } 
}
复制代码
package kaoshichengji;
 public class CatchWho2 { 
    public static void main(String[] args) { 
        try {
                try { 
                    throw new ArrayIndexOutOfBoundsException(); 
                } 
                catch(ArithmeticException e) { 
                    System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); 
                }
            throw new ArithmeticException(); 
        } 
        catch(ArithmeticException e) { 
            System.out.println("发生ArithmeticException"); 
        } 
        catch(ArrayIndexOutOfBoundsException e) { 
            System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); 
        } 
    } 
}