views:

25

answers:

4

in a standard try-catch-error-block, how can i advice the programm to do something only, if no error is thrown ?

for example, if i want to configure a proxy for something ip-based, and if it all works, it should grey-out the button.

+1  A: 

set a variable to true first, i.e. noError = true

if any errors occurred, set it to false

PeterWong
BOOL noerror = TRUE; @try { [self setup:communicator]; } @catch (ICEException * ex) { noerror = FALSE; [self performSelectorOnMainThread:@selector(exception:) withObject:[ex description] waitUntilDone:NO]; [communicator destroy]; self.communicator = nil; initCallBackButton.hidden = FALSE; } if (noerror) { initCallBackButton.hidden = TRUE; //wenn die session aufgebaut ist, blende den button aus }at least in this block, it doesn't work, but i can't really figure out, why ?this simple idea sounds at least correct
nico
actually I don't know the syntax of objective-c, but i guess that's right
PeterWong
A: 

I'd do it this way (c#, but the idea can be reused somewhere else)

try {
 try {
 // some code
 }
 catch 
 { throw; }


 // code, done only if there was no error
}
catch {
 // read the exception.
}
Yossarian
A: 

You simply put it into the try block, but after the statement that might throw. If it does, control flow will divert to the catch block and skip the later instruction. That't the way try is supposed to be used.

Of course, if you have multiple statements that might throw exceptions, and just stuff everything in one big hairy global try block, it becomes more difficult to identify the right spot. This is one of the reasons why the huge global try block is an Antipattern.

Kilian Foth
i think this is THE idea, i haven't found
nico
so, i tried it. does not work, the next instruction is called even if there is a exception
nico
Well, that's just not how exceptions work. Post your actual code please - we must be missing something. (For instance, if you are calling foreign functions in your try block, one of them might print a stacktrace of something, making it look like you received an exception. But if it did actually arrive in `your` block, it would be terminated.
Kilian Foth
A: 

ok

@Yossarian doesn't work.

@PeterWong yours works. the compiler is just not able to interpret if(noerror), it had to be if(noerror==false)

nico