java线程中try catch finally块和throw抛出异常

先看代码:

public class MyThread extends Thread{

    public static void main(String[] args) {

        Runnable runable = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("Thread starts executing...");
                        throw new RuntimeException("Exception happends");
                } finally {
                    System.out.println("Finally bolck is called.");
                }
            }
        };

        Thread thread = new Thread(runable);
        try {
            thread.start();
        } catch (Exception e) {
            System.out.println("Exception is caught.");
        }finally{
            System.out.println("This is finally block.");
        }
    }
}

执行结果是
这里写图片描述

剖析这段代码:

  1. 调用对象的start()方法来启动一个线程,然后通过该对象所对应的方法run()来完成其操作的。所以代码先执行thread.start(), 然后执行run().
  2. 对于try+catch+finally,其运行流程:运行到try块中,如果有异常抛出,则转到catch块,catch块执行完毕后,执行finally块的代码,再执行finally块后面的代码;如果没有异常抛出,执行完try块,也要去执行finally块的代码。然后执行finally块后面的语句。
  3. throw抛出异常: throw是语句抛出一个异常。
    语法:throw new Exception();

Refrence:
Thread的run()与start()的区别
Java中try,catch,finally的用法
Java异常之try,catch,finally,throw,throws

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值