Creating Exceptions(建立一个异常)
视频锁定
{$ currentTime | date:'mm:ss' $}
{$ timeLeft | date:'mm:ss' $}
如果你想明确的让一个异常发生,非常简单,你创建一个NSException类的对象,并向这个对象发送raise消息就可以了。代码如下:
NSException myException = [[NSException alloc]
initWithName: @"My Exception"
reason: @"[Description of the cause...]"
userInfo: nil];
[myException raise];
// 在这之后的代码将不会被执行..
上面代码中的userInfo参数是NSDictionary类的key-value(键-值)对,它包含了关于应用程序特定的一些额外信息。你可以在你的程序中随意使用这个参数,这个参数对程序员来说非常方便,它更应该称为developerInfo..。
还有一种方法,你可以通过NSException的类方法+raise直接建立一个异常并抛出这个异常,代码如下:
[NSException raise: @"My Exception"
format: @"Parse error occurred at line %d.",lineNumber];
这里的format的参数可以用类似printf函数的功能格式化一个字符串。
通常情况下,你不应该给异常起个随意的名字,Objective-C中在NSException.h文件中,定义了很多异常的名字常量,如下:
NSCharacterConversionException
An exception when character set conversion fails.
NSGenericException
A generic exception for general purpose usage.
NSInternalInconsistencyException
An exception for cases where unexpected state is detected within an object.
NSInvalidArgumentException
An exception used when an invalid argument is passed to a method or function.
NSMallocException
An exception used when the system fails to allocate required memory.
NSParseErrorException
An exception used when some form of parsing fails.
NSRangeException
An exception used when an out-of-range value is encountered.
Also, some Foundation classes define their own more specialized exceptions:
NSFileHandleOperationException (NSFileHandle.h)
An exception used when a file error occurs.
NSInvalidArchiveOperationException (NSKeyedArchiver.h)
An archiving error has occurred.
NSInvalidUnarchiveOperationException (NSKeyedUnarchiver.h)
An unarchiving error has occurred.
NSPortTimeoutException (NSPort.h)
Exception raised if a timeout occurs during a port send or receive operation.
NSUnknownKeyException (NSKeyValueCoding.h)
An exception for an unknown key。
在线练习
{$ activeFileHint $}