1

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?

Kamilski81
  • 14,409
  • 33
  • 108
  • 161
  • Possible duplicate of [How to catch an Exception from a thread](http://stackoverflow.com/questions/6546193/how-to-catch-an-exception-from-a-thread) – pczeus Feb 15 '16 at 23:07
  • I'm leaning against closing as dupe, catching an exception somehow somewhere is a different question than catching one in another thread (even if the answer is you can't.) – djechlin Feb 15 '16 at 23:10
  • Why does a method named "onSensorChanged()" unconditionally throw an exception? That smells wrong. – Solomon Slow Feb 16 '16 at 14:53

1 Answers1

3

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 (i.e. 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.

djechlin
  • 59,258
  • 35
  • 162
  • 290