【问题标题】:How do I handle exceptions in a thread?如何处理线程中的异常?
【发布时间】:2014-10-25 17:37:03
【问题描述】:
我正在开发一个 Android 应用程序。我有一个具有这种结构的线程:
code...
try
code...
catch
printexception
code...
try
code...
catch
printexception
code..
当我遇到这些异常之一时,我知道我的代码的其余部分将不起作用并且不应该被执行。遇到异常时如何停止线程?我是否必须创建一个包含所有代码的“大尝试”?我一直在研究这样的代码一段时间,但我以前从未关心过异常。有什么好的、干净的方法来完成这个?
【问题讨论】:
标签:
java
android
multithreading
exception-handling
【解决方案1】:
这很简单,试试这个:
public static void main(String[] args) {
Thread thread = new Thread(new RunnableTest());
thread.start();
}
static class RunnableTest implements Runnable {
@Override
public void run() {
int i;
try {
i = 1 / 0;
} catch (Throwable t) {
t.printStackTrace();
return;
}
System.out.println(i);
}
}
为了更好地控制线程,您可以使用 java.util.Concurreent 包中的 Executors 和 ThreadPoolExecutors!
【解决方案2】:
一般来说,每当你尝试编码时,你应该将它们保持在 try 中,然后在 catch 下得到结果。
类似:
try
{
int x = 5/0;
}
catch(Exception e)
{
e.printStackTrace();
}
通过提及 printStackTrace,您可以获得行号以及异常的描述。我希望我说清楚了。
【解决方案3】:
如果您发布的代码存在于您的 run() 方法中,您只需在发生异常时提前返回,从而导致线程完成并避免执行任何后续代码。
code...
try {
code...
} catch (Exception e) {
e.printStackTrace();
return;
}
code...
您还可以在发生异常时设置一个标志,并定期检查该标志以确定您的线程是否应该继续运行。
bool isCanceled = false;
void run() {
while (!isCanceled) {
doSomeWork();
}
}
void doSomeWork() {
try {
code...
} catch (Exception e) {
e.printStackTrace();
isCanceled = true;
return;
}
}
当然,您也可以对代码进行结构化,以便任何依赖于上面语句的语句也在 try 块中。如果发生异常,控制流将转移到 catch 块,并且 try 块中任何跟在违规行后面的语句都不会被执行。我认为这就是您所说的包含所有代码的“大尝试”。
code...
try
code...
try // this try won't be executed if the line above it throws an exception
code...
catch {
printexception
return
}
code..
catch {
printexception
return // return early
}
code....