定义异常类模板
//编译时异常继承Exception(多数情况),运行时异常继承RuntimeException
public class MyException extends Exception{
public MyException(){}
public MyException(String s){
super(s);
}
}
在使用时抛出
//在使用时要将异常抛出
public class Text {
public void doException() throws MyException {
MyException e = new MyException("出现一个错误");
throw e;
}
}
当调用方法时try/catch并打印信息
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btSend);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Intent intent = new Intent("B");
// sendBroadcast(intent);
//
Text text = new Text();
try {
text.doException();
} catch (MyException e) {
//打印信息或者执行操作
Log.d("TAG", "onClick: =============================执行发生异常之后的操作");
}finally {
//一定会执行的逻辑
Log.d("TAG", "onClick: ========================解决方法");
}
}
});
}
}