Board index » delphi » Re(2): Try...Finally: should I ever use ?

Re(2): Try...Finally: should I ever use ?

Hmm.. but what if you rewrite your code like this:

begin

Quote

  myList := tStringList.Create;
  try
    // do my list work
  except
    // Do some error handling here, if you feel like. Otherwise leave this
blank.
  end;
  myList.Free;
end;

Notice that myList.Free will be executed regardless of exceptions in the
try..except code, safely releasing your resources.

It may be argued that it's not an elegant solution to use an empty except
block, in case you don't want to do any kind of error-handling, so it
would be more elegant to use a try..finally block (which would have no
empty blocks). However, I usually won't let an exception go unnoticed, so
I seldom use a try...finally block.
Any other reasons to use Try..Finally blocks?

Quote
>no.junk.please....@attcanada.net writes:
>I use try finally even more than try except. Its particularly useful for
>freeing resources. Whenever I get a resource, I always follow the
>allocation
>with a try finally that releases the resource, e.g.

>myList := tStringList.Create;
>try
>    // do my list work
>finally
>    myList.Free;
>    end;

>This section of code assures me that the string list will always be
>released, regardless of what happens in the code.

-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-

              Elifarley C. Coelho
      Software Development - Metalink
        Belo Horizonte - Brazil
       elifar...@NOSPAM.metalink.com.br

-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-

 

Re:Re(2): Try...Finally: should I ever use ?


Elifarley C. Coelho <elifar...@delphi.com.br> wrote in message
news:fc.004c4f74001793bc004c4f7400178c97.1793f7@delphi.com.br...

Quote
> Hmm.. but what if you rewrite your code like this:

> begin

>   myList := tStringList.Create;
>   try
>     // do my list work
>   except
>     // Do some error handling here, if you feel like. Otherwise leave this
> blank.
>   end;
>   myList.Free;
> end;

> Notice that myList.Free will be executed regardless of exceptions in the
> try..except code, safely releasing your resources.

> It may be argued that it's not an elegant solution to use an empty except
> block, in case you don't want to do any kind of error-handling, so it
> would be more elegant to use a try..finally block (which would have no
> empty blocks). However, I usually won't let an exception go unnoticed, so

Using the scheme you suggest above makes it very difficult to notice an
exception that you don't check for in the except. (Its also more typing.)
The only way you might notice it is when you discover that your code isn't
doing what its supposed to do. Using try finally will free the list
resources and still present you with the exception.

Quote
> I seldom use a try...finally block.
> Any other reasons to use Try..Finally blocks?

I repeat my suggestion that using try finally helps to elimate resource
leakage in programs. If you always use the template

allocate a resource
try
    use the resource
finally
    free the resource

you can be assured that those resources are freed.

I also use try finally when changing the mouse cursor, displaying progress
messages, openning files, etc., e.g.

svCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
try
    // do some lengthy work
finally
    Screen.Cursor := svCursor;
    end;

myStatusBar.SimpleText := 'Doing something';
try
    // do something
finally
    myStatusBar.SimpleText := '';
    end;

ReWrite (myFile);
try
    // write to myFile
finally
    CloseFile (myFile);
    end;

- Show quoted text -

Quote

> >no.junk.please....@attcanada.net writes:
> >I use try finally even more than try except. Its particularly useful for
> >freeing resources. Whenever I get a resource, I always follow the
> >allocation
> >with a try finally that releases the resource, e.g.

> >myList := tStringList.Create;
> >try
> >    // do my list work
> >finally
> >    myList.Free;
> >    end;

> >This section of code assures me that the string list will always be
> >released, regardless of what happens in the code.

> -/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-

>               Elifarley C. Coelho
>       Software Development - Metalink
> Belo Horizonte - Brazil
>        elifar...@NOSPAM.metalink.com.br

> -/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-

Re:Re(2): Try...Finally: should I ever use ?


In article <fc.004c4f74001793bc004c4f7400178c97.179...@delphi.com.br>,
elifar...@delphi.com.br (Elifarley C. Coelho) writes:

Quote
> myList := tStringList.Create;
>  try
>    // do my list work
>  except
>    // Do some error handling here, if you feel like. Otherwise leave this
blank.
>  end;
>  myList.Free;
>end;

>Notice that myList.Free will be executed regardless of exceptions in the
>try..except code, safely releasing your resources.

Not so.

Any exception which you do not catch in the except clause will bypass the
remaining code, looking for a handler of that exception. If none is found in
your code, then Delphi's default handling will occur.

try / except is for use when you want to handle exceptions in some way (ignore,
display more information, recover after informing, inform & re-raise, prevent
Delphi raising an exception etc) different from the way Delphi handles it.

try / finally is for situations where, regardless of any exception, some code
_must_ be executed even if an exception is triggered.

BTW note that even if you catch an exception in your code, in the IDE Delphi
will also handle it and display its error message.

Alan Lloyd
alangll...@aol.com

Re:Re(2): Try...Finally: should I ever use ?


There is another advantage of using try..finall - if the code
contains Exit, the finally block will execute whereas with
the exception handling the exit will leave the procedure
right away.

Quote
AlanGLLoyd <alangll...@aol.com> wrote:

: In article <fc.004c4f74001793bc004c4f7400178c97.179...@delphi.com.br>,
: elifar...@delphi.com.br (Elifarley C. Coelho) writes:

:> myList := tStringList.Create;
:>  try
:>    // do my list work
:>  except
:>    // Do some error handling here, if you feel like. Otherwise leave this
: blank.
:>  end;
:>  myList.Free;
:>end;
:>
:>Notice that myList.Free will be executed regardless of exceptions in the
:>try..except code, safely releasing your resources.

: Not so.

: Any exception which you do not catch in the except clause will bypass the
: remaining code, looking for a handler of that exception. If none is found in
: your code, then Delphi's default handling will occur.

: try / except is for use when you want to handle exceptions in some way (ignore,
: display more information, recover after informing, inform & re-raise, prevent
: Delphi raising an exception etc) different from the way Delphi handles it.

: try / finally is for situations where, regardless of any exception, some code
: _must_ be executed even if an exception is triggered.

: BTW note that even if you catch an exception in your code, in the IDE Delphi
: will also handle it and display its error message.

: Alan Lloyd
: alangll...@aol.com

Re:Re(2): Try...Finally: should I ever use ?


Quote
AlanGLLoyd wrote:
> In article <fc.004c4f74001793bc004c4f7400178c97.179...@delphi.com.br>,
> elifar...@delphi.com.br (Elifarley C. Coelho) writes:

> > myList := tStringList.Create;
> >  try
> >    // do my list work
> >  except
> >    // Do some error handling here, if you feel like. Otherwise leave this
> blank.
> >  end;
> >  myList.Free;
> >end;

> >Notice that myList.Free will be executed regardless of exceptions in the
> >try..except code, safely releasing your resources.

> Not so.

> Any exception which you do not catch in the except clause will bypass the
> remaining code, looking for a handler of that exception.

    If the code is as above then there _are_ no exceptions that are not
caught in the except part. The fact that every exception _is_ handled is
exactly what's _wrong_ with trying to use "except" instead of "finally"
this way! A finally block is not _supposed_ to handle exceptions -
if we use this substitute for a finally block then we're handing
exceptions that we should _not_ be handling.

    Look what happens:

s:= TStringlist.Create;
try
  SomethingWrongThatRaisesException;
except
end;
s.Free;
MoreCode;

s:= TStringlist.Create;
try
  SomethingWrongThatRaisesException;
finally
  s.Free;
end;
MoreCode;

    We agree that the "finally" version is right. But getting straight
_why_ it's right could be useful. In the "except" version the
MoreCode _is_ executed. It _is_ executed because the exception
_was_ handled by the except block.(!) And the fact that MoreCode
is executed is a bad thing, because MoreCode could be depending
on _successful_ execution of the "try" part - if MoreCode is
executed after the error in the "try" block that could lead to
worse errors.

    If you do it right, using "finally", then it's _ok_ for MoreCode
to assume that the try block executed successfully, because if it
didn't then MoreCode will never be executed - the exception
takes us out of the current block. (After executing the finally
part.)

Quote
> If none is found in
> your code, then Delphi's default handling will occur.

> try / except is for use when you want to handle exceptions in some way (ignore,
> display more information, recover after informing, inform & re-raise, prevent
> Delphi raising an exception etc) different from the way Delphi handles it.

> try / finally is for situations where, regardless of any exception, some code
> _must_ be executed even if an exception is triggered.

    Everybody including the original poster understands this. The
question was why the version that seems to fake a "finally"
using "except" doesn't work. Explaining what the things
were intended for doesn't explain why the wrong version
doesn't work.

Quote
> BTW note that even if you catch an exception in your code, in the IDE Delphi
> will also handle it and display its error message.

    Or not, depending on the whether BreakOnException is set..

- Show quoted text -

Quote

> Alan Lloyd
> alangll...@aol.com

Re:Re(2): Try...Finally: should I ever use ?


Quote
"Elifarley C. Coelho" wrote:
> Hmm.. but what if you rewrite your code like this:

> begin

>   myList := tStringList.Create;
>   try
>     // do my list work
>   except
>     // Do some error handling here, if you feel like. Otherwise leave this
> blank.
>   end;
>   myList.Free;
> end;

> Notice that myList.Free will be executed regardless of exceptions in the
> try..except code, safely releasing your resources.

    That's correct, people's posts to the contrary notwithstanding.

Quote
> It may be argued that it's not an elegant solution to use an empty except
> block, in case you don't want to do any kind of error-handling, so it
> would be more elegant to use a try..finally block (which would have no
> empty blocks). However, I usually won't let an exception go unnoticed, so
> I seldom use a try...finally block.
> Any other reasons to use Try..Finally blocks?

    It's not just elegance, your version doesn't work right. I've explained
why in two posts so far - see my reply to Alan, that one may be
easier to follow because I give an explicit example.

    (Um, I believe the guy who pointed out that "finally" blocks are
executed after an Exit had a valid point as well. But there's more
to it than that, the way you suggest faking "finally" with
"except" simply doesn't work right.)

Re:Re(2): Try...Finally: should I ever use ?


Im Artikel <fc.004c4f74001793bc004c4f7400178c97.179...@delphi.com.br>,
elifar...@delphi.com.br (Elifarley C. Coelho) schreibt:

Quote
>>Notice that myList.Free will be executed regardless of exceptions in the

try..except code, safely releasing your resources.<<

AFAIR the subroutine is exited in case of an unhandled exception, or when an
exception handler will Raise the exception again.

Quote
>Any other reasons to use Try..Finally blocks?

As I was told on my first (similar) question about Try...Except/Finally, it's
often required to nest one in the other, to achieve both proper clean up of the
affected data structures, regardless of the kind of exception, and handling of
expected exceptions, at the same time.

DoDi

Re:Re(2): Try...Finally: should I ever use ?


Quote
AlanGLLoyd wrote:

> BTW note that even if you catch an exception in your code, in the IDE Delphi
> will also handle it and display its error message.

Provided "Break on exception" is set in the environemnt options. There
are sometimes occasions where you don't want the IDE to always stop on
these, especially if your code has various sorts of errors that result
in exceptions which do not occur *that* exceptionally (eg once every 5
mins of use or so...).

Of course exceptions do incur a performance overhead, so they shouldn't
be used in order to perform a logical calculation.

MH.

--
Martin Harvey.
mar...@aziraphale.demon.co.uk
mc...@harvey27.demon.co.uk
http://www.harvey27.demon.co.uk/mch24/

Re:Re(2): Try...Finally: should I ever use ?


In article <37B9DB8F.2826A...@aziraphale.demon.co.uk>, Martin Harvey

Quote
<mar...@aziraphale.demon.co.uk> writes:
>Of course exceptions do incur a performance overhead, so they shouldn't
>be used in order to perform a logical calculation.

>MH.

So to do this:

try
  exAngle:=  RadToDeg(arctan((Finish.X - Start.X)/ (Finish.Y - Start.Y))) +
270;
except on  EZeroDivide do
  begin
    exAngle:= 0;
    end;
    end;

Would be quicker like this

  if Finish.Y - Start.Y = 0 then
        then exAngle:= 0
  else
        exAngle:=  RadToDeg(arctan((Finish.X - Start.X)/ (Finish.Y - Start.Y)))
+ 270;

??

I do this in a MouseMove Event so speed does matter.

Gordon.
~~~~~~~~~~~~~~~~~~~~~~~~
Certifiable - definitely <g>

http://members.aol.com/mgcsoft/  (the function junction equation editor)
http://members.aol.com/delphistuf/delphstf.htm   (Delphi bits and bobs and a
few links)

MGCSoft

Re:Re(2): Try...Finally: should I ever use ?


Quote
AlanGLLoyd <alangll...@aol.com> wrote in message

news:19990817022313.16931.00000451@ngol02.aol.com...

Quote
> In article <fc.004c4f74001793bc004c4f7400178c97.179...@delphi.com.br>,
> elifar...@delphi.com.br (Elifarley C. Coelho) writes:

> > myList := tStringList.Create;
> >  try
> >    // do my list work
> >  except
> >    // Do some error handling here, if you feel like. Otherwise leave
this
> blank.
> >  end;
> >  myList.Free;
> >end;

> >Notice that myList.Free will be executed regardless of exceptions in the
> >try..except code, safely releasing your resources.

> Not so.

> Any exception which you do not catch in the except clause will bypass the
> remaining code, looking for a handler of that exception. If none is found
in
> your code, then Delphi's default handling will occur.

Unless you do something like

try
    // code
except
    // anything but "on exception do" and "raise"
    end;

in which case the except traps (and suppresses) all exceptions.

- Show quoted text -

Quote

> try / except is for use when you want to handle exceptions in some way
(ignore,
> display more information, recover after informing, inform & re-raise,
prevent
> Delphi raising an exception etc) different from the way Delphi handles it.

> try / finally is for situations where, regardless of any exception, some
code
> _must_ be executed even if an exception is triggered.

> BTW note that even if you catch an exception in your code, in the IDE
Delphi
> will also handle it and display its error message.

> Alan Lloyd
> alangll...@aol.com

Go to page: [1] [2]

Other Threads