2012-10-16 8 views
8

+[NSException exceptionWithName:reason:userInfo:]を使用します。Objective-CのNSExceptionの例外名にはどのような名前を使用しますか?

しかし、引数はどの文字列を使用しますか?Name:

例外名はプロジェクトで一意であるべきですか?
または、すべての例外に対して@ "MyException"を使用できますか?

そして、どの例外名が使用されているのか分かりません。
例外名はどこで使用されていますか?

答えて

6

@catch (NSException *theErr)の名前を使用できます。私は、引数名に使うべき文字列

@catch (NSException *theErr) 
{ 
    tst_name = [theErr name]; 
    if ([tst_name isEqualToString:@"name"]) 
} 

:?

意味があります。

プロジェクトで例外名を一意にする必要がありますか?

または私は私の例外のすべてのために "MyException" @使用できますか?

はい、意味のある名前を使用する必要があります。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
    // Insert code here to initialize your application 
    NSNumber *tst_dividend, *tst_divisor, *tst_quotient; 
    // prepare the trap 
    @try 
    { 
     // initialize the following locals 
     tst_dividend = [NSNumber numberWithLong:8]; 
     tst_divisor = [NSNumber numberWithLong:0]; 

     // attempt a division operation 
     tst_quotient = [self divideLong:tst_dividend by:tst_divisor]; 

     // display the results 
     NSLog (@"The answer is: %@", tst_quotient); 
    } 
    @catch (NSException *theErr) 
    { 
     // an exception has occured 
     // display the results 
     NSLog (@"The exception is:\n name: %@\nreason: %@" 
       , [theErr name], [theErr reason]); 
    } 
    @finally 
    { 
     //... 
     // the housekeeping domain 
     //... 
    } 
} 

- (NSNumber *)divideLong:(NSNumber *)aDividend by:(NSNumber *)aDivisor 
{ 
    NSException *loc_err; 
    long  loc_long; 

    // validity check 
    loc_long = [aDivisor longValue]; 
    if (loc_long == 0) 
    { 
     // create and send an exception signal 
     loc_err = [NSException 
        exceptionWithName:NSInvalidArgumentException 
        reason:@"Division by zero attempted" 
        userInfo:nil]; 
     [loc_err raise]; //locate nearest exception handler, 
     //If the instance fails to locate a handler, it goes straight to the default exception handler. 
    } 
    else 
     // perform the division 
     loc_long = [aDividend longValue]/loc_long; 

    // return the results 
    return ([NSNumber numberWithLong:loc_long]); 
} 

Understanding Exceptions and Handlers in Cocoa

+0

あなたの答えに感謝します! リンクも便利です。 [NSRangeException]のような[定義済みの例外名](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html)の使用を推奨します。[page2 ](http://macdevcenter.com/pub/a/mac/2007/07/31/understanding-exceptions-and-handlers-in-cocoa.html?page=2)。 –

1

を見てみましょう最終的には、このように例外を追加することの目的は、できるだけ早く問題を検出し、それを報告し、診断を可能にすることです。

このように、プロジェクトに固有の例外名を選択するか、問題(つまり、ソース行、メソッド)に固有の例外名を使用するかは、最適な診断情報を提供するものに依存します。

例外名は、例外が発生した場所を特定するためにアプリケーションによって報告されるため、アプリ全体で共有することができます。

関連する問題