[英]How can I catch a RuntimeException that is thrown inside a different thread?
Some pseudocode of what i'm doing, 我正在做的一些伪代码,
public class MeasurementDevice implements SensorEventListener {
public MeasurementDevice() {
mSensorManager = (SensorManager) mApplicationContext.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
HandlerThread mHandlerThread = new HandlerThread("sensorThread");
mHandlerThread.start();
Handler handler = new Handler(mHandlerThread.getLooper());
mSensorManager.registerListener(this, mAccelerometer, samplingPeriodHint, handler);
mSensorManager.registerListener(this, mGyroscope, samplingPeriodHint, handler);
}
@Override
public void onSensorChanged(SensorEvent event) {
throw new RuntimeException();
}
}
But when the exception is thrown, i'm not really sure how I can catch it? 但是当抛出异常时,我不确定我怎么能抓到它? Any ideas?
有任何想法吗?
Literally speaking, you absolutely can't. 从字面上讲,你绝对不能。 Exceptions are thread-specific constructs.
例外是特定于线程的构造。 You would need any other form of inter-thread communication in Java.
您将需要Java中的任何其他形式的线程间通信。
This, of course, is the only thing that makes sense: exception throwing is a control flow mechanism that pops out of the stack. 当然,这是唯一有意义的事情:异常抛出是一种从堆栈中弹出的控制流机制。 If an exception happens in one thread, what do you want another thread to do?
如果在一个线程中发生异常,那么您希望另一个线程做什么? Terminate suddenly then jump to some unrelated exception handling code?
突然终止然后跳转到一些不相关的异常处理代码?
Of course you may want another chunk of code (ie class) to handle the exception, but this isn't a question of what thread the code is running on. 当然,您可能需要另一块代码(即类)来处理异常,但这不是代码运行的线程的问题。 That is of course possible, and IIRC it involves letting the exception propagate and using
Thread.uncaughtExceptionHandler
as a global router. 这当然是可能的,而IIRC涉及让异常传播并使用
Thread.uncaughtExceptionHandler
作为全局路由器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.