在Java编程中,如何使用线程异常?

此示例显示如何在处理线程时处理异常。

package com.yiibai;

class MyThread extends Thread {
    public void run() {
        System.out.println("Throwing in " + "MyThread");
        throw new RuntimeException();
    }
}

public class ExceptionWithThread {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start();
        try {
            Thread.sleep(1000);
        } catch (Exception x) {
            System.out.println("Caught it" + x);
        }
        System.out.println("Exiting main");
    }
}
Java

上述代码示例将产生以下结果 -

Throwing in MyThreadException in thread "Thread-0" 
java.lang.RuntimeException
    at com.yiibai.MyThread.run(ExceptionWithThread.java:6)
Exiting main

相关文章:

  • 2022-12-23
  • 2021-10-24
  • 2022-12-23
  • 2021-07-06
  • 2021-09-22
  • 2022-02-18
  • 2021-10-08
  • 2021-06-11
猜你喜欢
  • 2021-05-04
  • 2022-01-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
相关资源
相似解决方案