【问题标题】:access objective-c exception in finally block在finally块中访问objective-c异常
【发布时间】:2009-04-22 20:22:38
【问题描述】:

鉴于以下情况:

@try {
    @try {
        // raises an exception :)
        [receiver raisingFirstException];
    } @finally {
        // raises another exception :)
        [otherReceiver raisingFinalException];
    }
} @catch (id e) {
    printf("exception: %s\n", [[e stringValue] cString]);
}

有没有办法在 @finally 块或在 @catch 块中获取两个异常?

我有代码,其中 @finally 块会进行一些检查,这可能会引发 异常,但我不想丢失原始异常(根本原因)。

如果没有原始异常但检查失败,我想要 他们抛出的异常。

【问题讨论】:

    标签: objective-c exception


    【解决方案1】:

    执行此操作的最佳方法是将异常分配给可从块的其余部分访问的变量。

    NSException *ex;
    @try {
        @try {
            [someObject methodWhichCouldThrowException];
        } @catch (NSException *e) {
            ex = e;
        } @finally {
            [anotherObject methodWhichCouldThrowADifferentException];
        }
    } @catch (NSException *e) {
        // From here you can access both the exception thrown by 'someObject'
        // as well as the exception thrown by 'anotherObject'.
    }
    

    【讨论】:

    • 似乎我已经简化了我的例子太多了。第一个异常是由程序中其他地方的方法引发的。我将相应地编辑我的问题。
    • 但是你不能通过将'finally'块更改为'catch'块并将异常设置为那里的局部变量来做你想做的事吗?我将编辑我的回复。
    • 好的,这可能是一个选择。但是代码不会像现在这样简单:(。
    • 是的,嵌套异常代码从来都不漂亮。但实际上没有其他方法可以做到这一点。您必须放入大量“catch”块并维护对以后可能需要的任何异常的引用。
    • 在objective-c 异常存在之前,我使用了我自己的setjmp/longjmp 实现和一组宏。虽然宏几乎是神秘的,但我可以访问 finally 块中最终发生的异常:)。
    猜你喜欢
    • 2011-01-31
    • 2019-03-31
    • 2010-10-03
    • 2014-01-08
    • 2021-03-02
    • 1970-01-01
    • 2015-10-21
    相关资源
    最近更新 更多