Java程序发生异常就挂了吗?

Java程序发生异常就挂了吗?

为了验证程序不会挂,我写了个例子给大家看看。

 

测试代码:

 

import java.io.File;
import java.io.IOException;

/**
* Java
程序发生异常就挂了吗?
*
*/
publicclass TestException {
        
publicstaticvoid main(String[] args) {
                TestException te =
new TestException();
                String s = te.test();
                System.out.println(s);
        }

        
/**
         *
这个方法有异常,看看异常发生时候会不会执行到底,会不会返回个值?
         *
         * @return
一个字符串!
         */

        
public String test() {
                System.out.println(
">>>> start");
                
try {
                        test1();
                        File f =
null;
                        f.delete();
//                        int x = 10;
//                        int y = 0;
//                        int z = x / y;
                        System.out.println(
"计算完成了!");

                }
catch (Exception e) {
                        System.out.println(
"出异常挂了我如何处理呢?");
                        System.out.println(e);
                }
finally {
                        System.out.println(
"最后总要做的一件事。。。");
                }
                System.out.println(
">>>> end");
                
return"good!";
        }

        
/**
         *
抛个比较猛烈的异常看看程序会挂吗?
         *
         * @throws IOException
         */

        
publicvoid test1() throws IOException {
                
thrownew IOException();
        }
}


运行结果:

>>>> start
出异常挂了我如何处理呢?
java.io.IOException
最后总要做的一件事。。。
>>>> end
good!

Process finished with exit code 0

 

 

换个异常运行看看:

>>>> start
出异常挂了我如何处理呢?
java.lang.NullPointerException
最后总要做的一件事。。。
>>>> end
good!

Process finished with exit code 0

 

再换个控制针看看:

>>>> start
出异常挂了我如何处理呢?
java.lang.ArithmeticException: / by zero
最后总要做的一件事。。。
>>>> end
good!

Process finished with exit code 0

 

结果表明:程序仅仅跳过了try中发生异常以后的代码,在发生异常时候执行了处理语句块catch,在catch执行结束后接着执行了finally语句块,然后继续执行try...catch...finally之外的语句块。

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值