@throw 没有被@catch 块捕获?
@throw not caught by @catch block?
如果有这样的代码
@try
{
@throw [NSException new];
}
@catch (NSException ex)
{
NSLog(@"exception caught");
}
在这种情况下,代码不会转到@catch 块,而是应用程序崩溃。我们应该如何捕获@throw in objective-c
抛出的异常
您必须使用
初始化 NSException
@throw [NSException exceptionWithName:@"Exception!" reason:nil userInfo:nil];
或其他一些有效的方法来构造 Apple 文档 "Creating and Raising an NSException Object" 页面中列出的 NSException。 https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSException_Class/index.html#//apple_ref/occ/cl/NSException
[NSException new]
实例化一个 null
class 因为它不包含有用的信息。它 不会 生成 NSException
实例,因此您的:
@catch (NSException *ex)
{
NSLog(@"exception caught");
}
没用。但是,如果您使用:
@catch (id exception)
{
}
你会捕捉到这个空对象。
Handling Exceptions官方文档摘录:
You can have a sequence of @catch error-handling blocks. Each block
handles an exception object of a different type. You should order this
sequence of @catch blocks from the most-specific to the least-specific
type of exception object (the least specific type being id) ...
如果有这样的代码
@try
{
@throw [NSException new];
}
@catch (NSException ex)
{
NSLog(@"exception caught");
}
在这种情况下,代码不会转到@catch 块,而是应用程序崩溃。我们应该如何捕获@throw in objective-c
抛出的异常您必须使用
初始化 NSException@throw [NSException exceptionWithName:@"Exception!" reason:nil userInfo:nil];
或其他一些有效的方法来构造 Apple 文档 "Creating and Raising an NSException Object" 页面中列出的 NSException。 https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSException_Class/index.html#//apple_ref/occ/cl/NSException
[NSException new]
实例化一个 null
class 因为它不包含有用的信息。它 不会 生成 NSException
实例,因此您的:
@catch (NSException *ex)
{
NSLog(@"exception caught");
}
没用。但是,如果您使用:
@catch (id exception)
{
}
你会捕捉到这个空对象。
Handling Exceptions官方文档摘录:
You can have a sequence of @catch error-handling blocks. Each block handles an exception object of a different type. You should order this sequence of @catch blocks from the most-specific to the least-specific type of exception object (the least specific type being id) ...