Re: Try/Catch

new topic     » goto parent     » topic index » view thread      » older message » newer message
Spock said...

Ok. I think I got this right:

1 Add delete_routine() to libraries - cleanup happens automatically when atom leaves scope
Or
2 Use try/catch/finally - manually call cleanup routine

Let's say I'm too lazy to do 1 (or it'd be really awkward since my libraries usually return integers (object IDs) not pointers). So how will I know which cleanup routines to call in finally in 2?

Spock

That's entirely up to you, isn't it? You'd have to clean up whatever you started, correct?

The finally statement simply affords you that opportunity, and it is entirely optional.

atom x 
 
try 
 
    -- get our resource to work with 
 
    x = get_resource() 
 
    -- do several things with the resource 
    -- that might throw an exception here 
 
    step_1( x ) 
    step_2( x ) 
    step_3( x ) 
    step_4( x ) 
    step_5( x ) 
 
catch e 
 
    -- ERROR HANDLING CODE GOES HERE -- 
 
finally 
 
    -- our resource will always be freed here 
    -- (unless we encounter a fatal error) 
 
    if object( x ) then 
        free_resource( x ) 
    end if 
 
end try 

Now compare that code to this...

 
atom x = get_resource() 
 
if error_code != 0 then 
    -- ERROR HANDLING CODE GOES HERE -- 
    return -- just quit 
end if 
 
step_1( x ) 
 
if error_code != 0 then 
    -- ERROR HANDLING CODE GOES HERE -- 
    goto "cleanup" 
end if 
 
step_2( x ) 
 
if error_code != 0 then 
    -- ERROR HANDLING CODE GOES HERE -- 
    goto "cleanup" 
end if 
 
step_3( x ) 
 
if error_code != 0 then 
    -- ERROR HANDLING CODE GOES HERE -- 
    goto "cleanup" 
end if 
 
step_4( x ) 
 
if error_code != 0 then 
    -- ERROR HANDLING CODE GOES HERE -- 
    goto "cleanup" 
end if 
 
step_5( x ) 
 
if error_code != 0 then 
    -- ERROR HANDLING CODE GOES HERE -- 
    goto "cleanup" 
end if 
 
label "cleanup" 
free_resource( x ) 

I would prefer the first option, but right now I am bound to the second.

-Greg

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu