【发布时间】:2013-01-12 10:35:48
【问题描述】:
好的,在我的一个课程中,我想抛出一个 InterruptedException。我通过调用来做到这一点
thread.interrupt();
据我所知,这将引发 InterruptedException。我想知道的是如何在我的线程中捕获这个异常。这显然行不通:
public void run() throws InterruptedException // This results in an error
编辑:如果我在我的线程中使用 try/catch 块,如果我从不声明它被抛出,我怎么能捕捉到一个中断的异常?
【问题讨论】:
-
你熟悉
try/catch语句吗? -
用 try and catch 包围
-
是的,我是。但是,我应该如何捕获从未声明为抛出的异常?
-
try { code } catch (RuntimeException ex) { do something with ex }或者甚至只是try { code } catch (Throwable t) { do something with t },如果你想真正去做的话。只要确保你在抓到ex或t后对其进行处理;如果需要,至少ex.printStackTrace()或t.printStackTrace();不过,InterruptedException预计会被抛出并用作指标。阅读线程。 -
@user1420042 你可以通过链接异常再次抛出异常,但是你的方法需要声明'throws InteruptedException'并且你需要在某个时候处理异常。
标签: java multithreading exception