简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM