版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ecnuThomas/article/details/71023539
先看代码:
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.");
}
}
}
执行结果是
剖析这段代码:
- 调用对象的start()方法来启动一个线程,然后通过该对象所对应的方法run()来完成其操作的。所以代码先执行thread.start(), 然后执行run().
- 对于try+catch+finally,其运行流程:运行到try块中,如果有异常抛出,则转到catch块,catch块执行完毕后,执行finally块的代码,再执行finally块后面的代码;如果没有异常抛出,执行完try块,也要去执行finally块的代码。然后执行finally块后面的语句。
- throw抛出异常: throw是语句抛出一个异常。
语法:throw new Exception();
Refrence:
Thread的run()与start()的区别
Java中try,catch,finally的用法
Java异常之try,catch,finally,throw,throws