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

来源:互联网 发布:手机模板软件 编辑:程序博客网 时间:2024/05/18 18:53

先看代码:

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

0 0
原创粉丝点击