【问题标题】:@throw not caught by @catch block?@throw 没有被@catch 块捕获?
【发布时间】:2016-05-20 07:27:14
【问题描述】:

如果有类似的代码

@try
{
    @throw [NSException new];
}
@catch (NSException ex)
{
    NSLog(@"exception caught");
}

在这种情况下,代码不会转到@catch 块,而是应用程序崩溃。我们应该如何在objective-c中捕获@throw抛出的异常

【问题讨论】:

    标签: objective-c try-catch nsexception


    【解决方案1】:

    [NSException new] 实例化一个null 类,因为它不包含有用的信息。它不会生成NSException 实例,因此您的:

    @catch (NSException *ex)
    {
        NSLog(@"exception caught");
    }
    

    没用。但是,如果您使用:

    @catch (id exception)
    {
    
    }
    

    你会抓住这个空物体。

    摘自Handling Exceptions官方文档:

    您可以拥有一系列@catch 错误处理块。每块 处理不同类型的异常对象。你应该点这个 从最具体到最不具体的@catch 块序列 异常对象的类型(最不具体的类型是 id)...

    【讨论】:

    【解决方案2】:

    您必须使用

    初始化 NSException

    @throw [NSException exceptionWithName:@"Exception!" reason:nil userInfo:nil];

    或在 Apple 文档的“创建和引发 NSException 对象”页面中列出的其他有效构造 NSException 的方法。 https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSException_Class/index.html#//apple_ref/occ/cl/NSException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多