Is it a good practice to subclass from NSException

2020-03-30 08:17发布

问题:

Is it a good practice to subclass from NSException for app-specific exceptions? That way everything is centralized one class for easier management.

e.g.

@interface AppException : NSException

+ (AppException *)InvalidSomething;
+ (AppException *)InvalidSomething2;

@end

回答1:

No, it's not good to subclass NSException because it's a class that doesn't need to be any more specific than it already is. In addition, subclasses, as is noted in the documentation, may not receive proper call stack symbols if thrown:

NSException subclasses posing as the NSException class or subclasses or other API elements that interfere with the exception-raising mechanism may not get this information.

If you wish to have "predefined exceptions" to throw, you can write a macro on NSAssert.

#define BOAssert NSAssert(0, @"Something bad just happened");

If you need "application-specific exceptions," make a constant that you can pass to +raise:format:. Bear in mind, though, that Objective-C is not Java. Exceptions are not a means of control flow, and should never be used as such (nothing in Cocoa-Touch can be regarded as exception safe). Because exceptions are fatal, give serious thought to why you'd actually need to throw them, and in what situations -for example, UITableView throws exceptions when it is updated into an undefined state.