Skip to content
Exception Handling
step 1/5

Reading — step 1 of 5

Learn

~1 min readExceptions and File I/O

Object Pascal exception handling uses try/except/finally:

uses SysUtils;

begin
    try
        n := StrToInt(input);     // raises EConvertError on failure
        Process(n);
    except
        on E: EConvertError do
            WriteLn('bad number: ', E.Message);
        on E: Exception do
            WriteLn('unexpected: ', E.Message);
    end;
end.

Exception classes — all descend from Exception (in SysUtils):

  • EConvertError — string-to-number conversion
  • EDivByZero / EZeroDivide — division
  • ERangeError — out of range
  • EAccessViolation — null/bad pointer
  • EOutOfMemory

Custom exceptions:

type
    EValidationError = class(Exception)
    public
        FieldName: string;
        constructor CreateForField(const AField, AMessage: string);
    end;

constructor EValidationError.CreateForField(const AField, AMessage: string);
begin
    inherited Create(AMessage);
    FieldName := AField;
end;

raise to throw:

if age < 0 then
    raise EValidationError.CreateForField('age', 'cannot be negative');

finally for cleanup:

list := TList<integer>.Create;
try
    try
        ProcessList(list);
    except
        on E: Exception do begin
            LogError(E.Message);
            raise;        // re-raise
        end;
    end;
finally
    list.Free;
end;

Pattern: try-finally for cleanup, optionally nested with try-except for handling. Cleanup ALWAYS runs.

Avoid catching Exception unless you really must — too broad, masks programming errors. Catch specific subclasses.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…