Intent.getByteArrayExtra需要捕获哪些异常
前段时间检视代码过程中,一个同事使用到了Intent.getByteArrayExtra()。我当时也没怎么上心,觉得大家都是这么用,应该没啥问题。
哈哈~ 问题往往都是发生在你认为没问题的时候。
走读下具体实现,看看需要捕获哪些异常:
public @Nullable byte[] getByteArrayExtra(String name) {
return mExtras == null ? null : mExtras.getByteArray(name);
}
同样的,bundle没有实现,去找他父亲,看看他父亲有没有实现getByteArray
@Nullable
byte[] getByteArray(@Nullable String key) {
unparcel();//这个地方,我们上次已经说过,可能会有BadParcelableException,就不细说了
Object o = mMap.get(key);//接着看下ArrayMap的get()方法的实现
if (o == null) {
return null;
}
try {
return (byte[]) o;
} catch (ClassCastException e) {
typeWarning(key, o, "byte[]", e);
return null;
}
}
可以看出,BadParcelableException我们是得进行捕获了,这个是毋庸置疑的
@Override
public V get(Object key) {
final int index = indexOfKey(key);
return index >= 0 ? (V)mArray[(index<<1)+1] : null;
}
public int indexOfKey(Object key) {
return key == null ? indexOfNull()//2个三目运算符,key==null,则去获取indexOfNull()--null所对应的hashCode
: indexOf(key, mIdentityHashCode ? System.identityHashCode(key) : key.hashCode());
}
@UnsupportedAppUsage(maxTargetSdk = 28) // Use indexOf(null)
int indexOfNull() {
final int N = mSize;
// Important fast case: if nothing is in here, nothing to look for.
if (N == 0) {
return ~0;
}
int index = binarySearchHashes(mHashes, N, 0);//对面的女孩看过来...
// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index;
}
// If the key at the returned index matches, that's what we want.
if (null == mArray[index<<1]) {
return index;
}
// Search for a matching key after the index.
int end;
for (end = index + 1; end < N && mHashes[end] == 0; end++) {
if (null == mArray[end << 1]) return end;
}
// Search for a matching key before the index.
for (int i = index - 1; i >= 0 && mHashes[i] == 0; i--) {
if (null == mArray[i << 1]) return i;
}
// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return ~end;
}
private static final boolean CONCURRENT_MODIFICATION_EXCEPTIONS = true;
private static int binarySearchHashes(int[] hashes, int N, int hash) {
try {
return ContainerHelpers.binarySearch(hashes, N, hash);
} catch (ArrayIndexOutOfBoundsException e) {
if (CONCURRENT_MODIFICATION_EXCEPTIONS) {
throw new ConcurrentModificationException();
} else {
throw e; // the cache is poisoned at this point, there's not much we can do
}
}
}
咋一看,这个地方是可能抛出ArrayIndexOutOfBoundsException ,数组越界异常。
眼睛有时候也会骗人的哟~我们再仔细看下是否真的会抛越界异常
CONCURRENT_MODIFICATION_EXCEPTIONS 被定义为static final的静态常量,在类ArrayMap加载时就已经加载到了内存空间中。
我们可以理解他是个恒为true的常量。所以我认为,捕获"并发修改异常"就可以了。
有人肯定提出异议了,我反射,我setAccessible。我总能让他走到else分支。是的,源码都承认了你的说法
} else {
throw e; // the cache is poisoned at this point, there's not much we can do
}
综上所述:捕获BadParcelableException| ConcurrentModificationException即可