Exception
异常嘛,同学们都会抛。也会try,应该还会自定义。
关于面试
同学们应该常见到有throw和throws的区别吧?
throw,单数的,throws,复数的,就理解为复数后面可以跟多个异常,所以在方法声明上,而单数的后面跟一个异常,所以是在方法体内抛一个示例异常。
这样子,两个都知道了。一个是使用的地方不一样。throws在方法声明上,而throw在方法体内。
抛异常来返回值
其实异常也是一种返回值。
比如说:
private final int ZERO_MAX_TIME = 20;
private int zeroTime = 0;
public double check(double wristTemp, double boardTemp, double envTemp) throws TempValueException {
if (wristTemp == 0.0) {
zeroTime++;
return 0.0;
} else {
zeroTime = 0;
}
if (zeroTime > ZERO_MAX_TIME) {
//超过20次,我们就认为传感器检测不到温度了
zeroTime = 0;
throw new TempValueException(
mContext.getString(R.string.sensor_break) + ":" + wristTemp,
ERROR_HARD_WEAR_ERROR);
}
//对体温值进行检查,如果温度小于某个阀值
//那么我们认为用户佩戴时间不够长
if (wristTemp <= 32.0f) {
throw new TempValueException(
mContext.getString(R.string.wear_time_too_short) + ":" + wristTemp,
ERROR_WEAR_TIME_TOO_SHORT);
} else if (wristTemp > 39.0f) {
throw new TempValueException(
mContext.getString(R.string.body_sensor_value_too_high_text) + ":" + wristTemp,
ERROR_SENSOR_TOO_HIGH);
}
//如果电池温度小于腕温,那么我们认为传感器温度是不受影响的
//if (batteryTemp <= wristTemp) {
//当主板温度比较低的时候,可以认为主板对传感器温度不影响
// return wristTemp;
//}
//对主板温度值进行检查
if (envTemp > 37.2f) {
throw new TempValueException(
mContext.getString(R.string.board_temperature_high_text) + ":" + boardTemp,
ERROR_HARD_WEAR_TOO_HIGH);
}
return wristTemp;
}
自定义异常:
public static final int ERROR_HARD_WEAR_TOO_HIGH = 1;
public static final int ERROR_HARD_WEAR_ERROR = 2;
public static final int ERROR_SENSOR_TOO_HIGH = 3;
public static final int ERROR_SENSOR_TOO_LOW = 4;
public static final int ERROR_WEAR_TIME_TOO_SHORT = 5;
public static class TempValueException extends Exception {
private final int mCode;
public int getCode() {
return mCode;
}
public TempValueException(String description, int code) {
super(description);
this.mCode = code;
}
}
这样子,调用的地方可以try住异常,做为一个返回结果。携带一定的信息。
输出堆栈信息
这个可能我们要追踪调用栈的时候比较好用。
举个例子,如果你写了一个内容提供者,多个地方调用了。你设置数值为10的时候,你发现读取的时候是20了。
被其他地方也更新了,那么你如何知道是谁更新的呢?
我们使用内容提供者的时候,获取到contentResolver以后,然后去Insert/update。
那么在系统源里,这两个方法上加上以下代码,就可以知道是从哪里调用进来的了。
Log.d(TAG, "call stack==> " + Log.getStackTraceString(new Throwable()));
当然,你先判断一下Uri,否则log太多了。
由此一来,你就就找到了是谁调用过来的了。
在AOSP开发中,特别是项目被改得狗屎一样的代码,很经常用这种方式,或者打断点的方式去调试程序。