课后整理总结-10.17

异常处理-动手动脑问题

1.

运行AboutException.java

 

出现:数学运算异常——java.lang.ArithmeticException

原因是除数为0了

 

 2.

CatchWho.java

复制代码
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"); 
        } 
    } 
}
复制代码

运行结果:

ArrayIndexOutOfBoundsException/内层try-catch
发生ArithmeticException

CatchWho2.java

复制代码
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"); 
        } 
    } 
}
复制代码

程序运行的结果:

ArrayIndexOutOfBoundsException/外层try-catch

3.

EmbedFinally.java运行结果:

 

 finally语句块一定会执行吗?SystemExitAndFinally.java

复制代码
public class SystemExitAndFinally {
    public static void main(String[] args)
    {
        try{
            System.out.println("in main");
            throw new Exception("Exception is thrown in main");
                    //System.exit(0);
        }
        
        catch(Exception e)
            {
            
            System.out.println(e.getMessage());
            System.exit(0);
        }
        finally
        {
            System.out.println("in finally");
        }
    }
}
复制代码

 

运行结果:

 

 显然并不是一定执行。

存在很多特殊情况导致 finally 语句块不执行。如:

直接返回未执行到 try-finally 语句块
抛出异常未执行到 try-finally 语句块
系统退出未执行到 finally 语句块

 

作者:冰稀饭Aurora

出处:https://www.cnblogs.com/rsy-bxf150/p/16801042.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   冰稀饭Aurora  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示