匿名线程的异常
我试图用异常包围我的代码,这样我就不会出现任何内存泄漏。 我尝试了以下代码,由于某种原因,异常没有被处理,并且出现运行时错误。
一些代码:
try
{
methodA();
} catch (Throwable th)
{
MsgProxyLogger.error(TAG, th.getMessage());
}
}
protected void methodA()
{
Thread disptacherThread = new Thread()
{
@Override
public void run()
{
dispatcher.dispatch(existingMessagesArr);
}
};
disptacherThread.start();
}
现在如果线程内发生一些运行时异常,它不会被捕获在 throable 子句中?
这是为什么?匿名线程正在取消 catch 子句吗?
谢谢,
雷。
im trying to surround my code with exceptions all over so I wont have any memory leaks.
I tried the following code, and for some reason the exception isnt being handled and i get runtime error.
some code:
try
{
methodA();
} catch (Throwable th)
{
MsgProxyLogger.error(TAG, th.getMessage());
}
}
protected void methodA()
{
Thread disptacherThread = new Thread()
{
@Override
public void run()
{
dispatcher.dispatch(existingMessagesArr);
}
};
disptacherThread.start();
}
Now if some runtime exception occurse inside the thread, it wont be caught in the throable clauses ?
why is that? does Anonymous thread is canceling the catch clauses?
Thanks,
ray.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是没有。
try-catch 块只能捕获 Thread.Start() 方法(即内存不足)。但是一旦线程启动,或者更好的是,已安排启动,您将失去对它的控制。
如果 unhandlex 异常超出线程范围,您的 JVM 将崩溃。你应该用 try-catch 包围你的内部匿名方法。
希望对您有所帮助。
Unfortunately not.
The try-catch block is able to catch only up to Thread.Start() method (ie. out of memory). But once the thread is started, or better, has been scheduled for start, you will lose control of it.
If an unhandlex exception goes outside the thread scope your JVM will crash. You should surround your inner anonymous method with try-catch.
Hope to have been of help.
这是正确的。
try
/catch
只能捕获当前线程抛出的异常。匿名 Runnable 的run
方法中的代码在不同的线程上执行。解决方案有两种:
run
方法中放置try
/catch
来处理异常。ThreadGroup
注册一个UncaughtExceptionHandler
。顺便说一句,如果您担心异常导致资源泄漏,最好的解决方案是使用以下模式编写代码:
简单地捕获并记录异常(如示例代码所示)并不能解决资源泄漏问题。
That is correct. A
try
/catch
can only catch exceptions thrown by the current thread. The code in the anonymous Runnable'srun
method is executed on a different thread.There are two solutions to this:
try
/catch
in therun
method to deal with the exception.UncaughtExceptionHandler
either with the child thread, or itsThreadGroup
.Incidentally, if you are concerned with exceptions causing resource leaks, the best solution is to write your code using this pattern:
Simply catching and logging exceptions (as your example code does) will not cure a resource leak.