Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

Registriert seit: 5. Jan 2005
Ort: Stadthagen
9.454 Beiträge
 
Delphi 10 Seattle Enterprise
 
#3

AW: Wann werfe ich welche Exception?

  Alt 22. Mär 2013, 10:41
Das hängt von deinem Programmfluss selber ab und ob du diese Ausnahme (Exception) behandeln kannst/willst.

Nicht jede Exception bedeutet zwingend, dass alles für die Katz ist.

Hier mal ein kleines Beispiel:
Delphi-Quellcode:
program ExceptionTest;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils;

type
  ECalcError = class( Exception );

procedure LogCalc( a, b, r : Integer );
begin
  Write( a, ' div ', b, ' = ' );
  if a div b <> r
  then
    raise ECalcError.CreateFmt( '%d div %d <> %d', [a, b, r] );
  Writeln( r );
end;

procedure TestRun;
var
  LIdx : Integer;
begin
  try

    for LIdx := 1 to 10 do
      begin
        try

          LogCalc( Random( 10 ), Random( 10 ), Random( 2 ) );

        except
          on E : ECalcError do
            begin
              Writeln( 'Das war wohl nix (', E.Message, ')' );
            end;
        end;
      end;

  except
    Writeln( 'Fehler' );
    raise;
  end;

end;

begin
  try

    Randomize;
    TestRun;

  except
    on E : Exception do
      begin
        Writeln( E.ClassName, ': ', E.Message );
      end;
  end;

  ReadLn;

end.
Beispiel-Lauf:
Code:
6 div 4 = 1
5 div 9 = Das war wohl nix (5 div 9 <> 1)
0 div 5 = 0
6 div 6 = 1
8 div 1 = Das war wohl nix (8 div 1 <> 0)
9 div 4 = Das war wohl nix (9 div 4 <> 1)
2 div 0 = Fehler
EDivByZero: Division durch Null
Kaum macht man's richtig - schon funktioniert's
Zertifikat: Sir Rufo (Fingerprint: ‎ea 0a 4c 14 0d b6 3a a4 c1 c5 b9 dc 90 9d f0 e9 de 13 da 60)
  Mit Zitat antworten Zitat