我正在做的一些伪代码,
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();
}
}
但是当抛出异常时,我不太确定如何捕捉它?有什么想法吗?
最佳答案
从字面上来说,你绝对不能。异常是特定于线程的构造。您将需要 Java 中任何其他形式的线程间通信。
当然,这是唯一有意义的事情:异常抛出是一种从堆栈中弹出的控制流机制。如果一个线程发生异常,你想让另一个线程做什么?突然终止然后跳转到一些不相关的异常处理代码?
当然,您可能需要另一段代码(即类)来处理异常,但这不是代码在哪个线程上运行的问题。这当然是可能的,IIRC 涉及让异常传播并使用 Thread.uncaughtExceptionHandler
作为全局路由器。
关于java - 如何捕获在不同线程内抛出的 RuntimeException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420722/