关于捕捉全局异常

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Thread thread=new Thread(){
         @Override
         public void run() {
      ImageView image=(ImageView) findViewById(R.id.text);
          super.run();
         }
        };
        thread.setUncaughtExceptionHandler(this);
        thread.start();
        Button button=(Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener(){

     @Override
     public void onClick(View v) {
      ImageView image=(ImageView) findViewById(R.id.text);
      Log.e("onClick","image");
     }
         
        });
    }

  @Override
  public void uncaughtException(Thread thread,
    Throwable ex) {
   Log.e("MainActivity","-->"+ex.getMessage());
  }

UncaughtException 可以捕获未知异常,但是异常代码依然要放到run方法内部,以此为例,我的R.id.text是TextView转换成ImageView会报ClassCastException,把他放到run方法内部才能捕获到它,否则放到外边是捕获不到它的异常的。

 

通过调用Thread.setDefaultUncaughtExceptionHandler(this);可以捕捉到全局异常

你可能感兴趣的:(Exception篇)