Why is this an issue?
Throwing an exception from within a finally block will mask any exception which was previously thrown in the try
or catch
block, and the masked’s exception message and stack trace will be lost.
Noncompliant code example
void openResource() {
@throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil];
}
void fun() {
@try {
openResource();
}
@finally {
closeResource();
@throw ... ; // Noncompliant - will mask previous exception
}
}
Compliant solution
void openResource() {
@throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil];
}
void fun() {
@try {
openResource();
}
@finally {
closeResource();
}
}
Resources
- CERT, ERR05-J. - Do not let checked exceptions escape from a finally block