簡體   English   中英

如何捕獲在不同線程內引發的RuntimeException?

[英]How can I catch a RuntimeException that is thrown inside a different thread?

我正在做的一些偽代碼,

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作為全局路由器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM