对于特定于应用程序的异常,从NSException进行子类化是一个很好的做法吗? [英] Is it a good practice to subclass from NSException for app-specific exceptions?

查看:131
本文介绍了对于特定于应用程序的异常,从NSException进行子类化是一个很好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于特定于应用程序的异常,是否从NSException进行子类化是一个很好的做法?这样一来,一切都集中在一个课堂上,以便于管理。



例如

  @interface AppException:NSException 

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

@end


解决方案

否,因为它是一个不需要比它已经更具体的类的类,它不是很好的。另外,如文档中所指出的那样,子类可能不会收到正确的调用堆栈符号,如果抛出:


NSException子类构造为NSException类或子类
或其他影响异常处理
机制的API元素可能无法获取此信息。


如果你希望抛出预定义的异常,你可以在NSAssert上写一个宏。

  #define BOAssert NSAssert (0,@发生不好的事情); 

如果您需要特定于应用程序的异常,请保持不变,您可以传递到 +加注:格式:。请记住,Objective-C不是Java。异常不是控制流的手段,不应该这样使用(Cocoa-Touch中的任何东西都不能被视为异常安全)。因为异常是致命的,请认真思考为什么你真的需要抛出它们,并且在什么情况下 - 例如,当UITableView被更新为未定义状态时,它会抛出异常。


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

解决方案

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.

这篇关于对于特定于应用程序的异常,从NSException进行子类化是一个很好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆