← Back to fpsonar
try..except and try..finally are where Pascal code most often goes quietly
wrong: the mistakes compile, run, and hide the failure they were meant to surface.
Most rules here are off by default because they were added recently.
A note on the two forms, since the rules depend on the difference:
try..finally— the finally part always runs, whether or not an exception happened.
Use it to release things.
try..except— the except part runs only when an exception happened.
Use it to handle failures.
ExceptionsNotSwallowed
editmajor · on by default
An except block with nothing in it makes the exception disappear. The program
carries on as though the operation succeeded, and the eventual symptom appears
somewhere unrelated. If you genuinely want to ignore a failure, say so in a
comment — but an empty handler is almost always an unfinished thought.
fpsonar complains about this
try
LoadConfig;
except
end; // failure silently ignored
fpsonar accepts this
try
LoadConfig;
except
on E: Exception do
WriteLn('config not loaded: ', E.Message);
end;
NoEmptyFinally
editmajor · on by default
An empty finally does nothing, so the try around it does nothing either. It is
usually left behind after the cleanup it once held was moved or deleted.
fpsonar complains about this
try
Process;
finally
end;
fpsonar accepts this
try
Process;
finally
Cleanup;
end;
NoCatchRawException
editminor · on by default
Catching Exception catches everything — including failures you did not
anticipate and cannot handle sensibly, like out-of-memory. Catch the specific class
you know how to deal with and let the rest travel up.
fpsonar complains about this
try
Value := StrToInt(S);
except
on E: Exception do
Value := 0;
end;
fpsonar accepts this
try
Value := StrToInt(S);
except
on E: EConvertError do
Value := 0;
end;
NoRaiseRawException
editminor · on by default
The same argument on the raising side. raise Exception.Create(...) gives callers
nothing to match on, so their only option is to catch everything. Declare a class
for your failure.
fpsonar complains about this
if not FileExists(AName) then
raise Exception.Create('missing file');
fpsonar accepts this
type
EConfigMissing = class(Exception);
if not FileExists(AName) then
raise EConfigMissing.Create('missing file');
NoExplicitReRaise
editminor · on by default
Inside a handler, a bare raise re-raises the exception you caught, preserving it
exactly. Raising it by name — raise E — is not the same thing: it transfers
ownership and can lose the original stack context. Prefer the bare form.
fpsonar complains about this
except
on E: EConfigMissing do
begin
Log(E.Message);
raise E;
end;
end;
fpsonar accepts this
except
on E: EConfigMissing do
begin
Log(E.Message);
raise;
end;
end;
ExitInsideFinally
editmajor · off by default
If an exception is travelling and a finally block calls exit, the exception is
discarded — the routine returns normally and the caller never learns anything
failed. This is one of the most effective ways to lose an error in Pascal, and
nothing warns you.
fpsonar complains about this
try
Process;
finally
if not Valid then
exit; // swallows any in-flight exception
Cleanup;
end;
fpsonar accepts this
try
Process;
finally
if Valid then
Cleanup;
end;
RaiseInsideFinally
editmajor · off by default
Raising inside finally replaces the exception already travelling with the new
one. The original failure — usually the more informative of the two — is gone.
fpsonar complains about this
try
Process;
finally
if not Closed then
raise EIOError.Create('not closed'); // replaces the real failure
end;
fpsonar accepts this
try
Process;
finally
if not Closed then
Log('warning: not closed');
end;
HandlerOrderShadowsDerived
editmajor · off by default
Handlers are tried in order, and the first matching one wins. So a handler for a base class placed before one for its descendant makes the second unreachable: the base handler catches the descendant first. Order handlers most-specific first.
fpsonar complains about this
try
Load;
except
on E: Exception do Log(E.Message);
on E: EConfigMissing do UseDefaults; // never reached
end;
fpsonar accepts this
try
Load;
except
on E: EConfigMissing do UseDefaults;
on E: Exception do Log(E.Message);
end;
ExceptionClassNotDerivedFromException
editmajor · off by default
Pascal lets you raise any object, but the RTL's handling — the message property,
the default handler, the debugger integration — assumes a descendant of
Exception. Raising something else produces an object nobody can handle usefully.
fpsonar complains about this
type
TFailure = class(TObject)
end;
raise TFailure.Create;
fpsonar accepts this
type
EFailure = class(Exception)
end;
raise EFailure.Create('what went wrong');
EmptyTryBody
editminor · off by default
A try with nothing in it cannot fail, so the handler beside it can never run.
Like an empty finally, this is usually a leftover.
fpsonar complains about this
try
finally
Cleanup;
end;
fpsonar accepts this
Cleanup;
RaiseInDestructor
editmajor · off by default
A destructor often runs while an exception is already travelling — that is exactly
what finally and object cleanup are for. Raising a second exception from a
destructor at that moment loses the first, and in some paths terminates the
program. Log instead, or swallow deliberately.
fpsonar complains about this
destructor TFileWriter.Destroy;
begin
if not FClosed then
raise EIOError.Create('writer not closed');
inherited Destroy;
end;
fpsonar accepts this
destructor TFileWriter.Destroy;
begin
if not FClosed then
try
Close;
except
on E: Exception do Log(E.Message);
end;
inherited Destroy;
end;
TryFinallyAcquireOutsideTry
editminor · off by default
The acquire must happen before the try, not inside it. If it is inside and it
fails, finally still runs and releases something that was never acquired.
fpsonar complains about this
try
Lock.Acquire; // if this raises, Release still runs
Process;
finally
Lock.Release;
end;
fpsonar accepts this
Lock.Acquire;
try
Process;
finally
Lock.Release;
end;
AssertUsedForControlFlow
editmajor · off by default
Assert is removed entirely when compiled with {$C-} — which release builds
routinely do. So anything the asserted expression does, as opposed to checks,
stops happening in release. If the call matters, make it a statement of its own.
fpsonar complains about this
Assert(Connect(AHost), 'could not connect'); // Connect vanishes under {$C-}
fpsonar accepts this
if not Connect(AHost) then
raise EIOError.CreateFmt('could not connect to %s', [AHost]);
Related chapters
editAssertWithoutMessage is in calling RTL routines. Rules about freeing the
exception object, and about reusing an exception instance after raising it, are in
memory and lifetime.
See also
edit- fpsonar — what fpSonar is, and how to run it
← Back to fpsonar