如何处理线程中的异常?

时间:2014-10-25 17:37:04

标签: java android multithreading exception-handling

我正在使用Android应用。我有一个这种结构的线程:

code...
try
    code...
catch
    printexception
code...
try
    code...
catch
    printexception
code..

当我遇到其中一个异常时,我知道我的代码的其余部分将无法工作且不应执行。遇到异常时如何阻止线程?我是否必须创造一个"大尝试"包含所有代码?我已经在这样的代码上工作了一段时间,但我以前从未关心异常。实现这一目标的好方法是什么?

3 个答案:

答案 0 :(得分: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包中的ExecutorsThreadPoolExecutors

答案 1 :(得分:0)

通常,无论何时尝试编码,都应该保留它们,然后在catch下获取结果。

就像:

try
{
int x = 5/0;
}
catch(Exception e)
{
e.printStackTrace();
}

通过提及printStackTrace,您可以获取行号以及异常的描述。我希望我明白我的观点。

答案 2 :(得分:0)

如果您发布的代码存在于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块,并且执行块中跟随违规行的任何语句都不会被执行。我认为这就是你所说的“大尝试”#34;包含所有代码。

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....