Exception handling

Top  Previous  Next

What is translated > Exception handling

Delphi uses structured exception handling with the try..except and try..finally blocks, similar to other high-level languages. Exceptions are objects, typically descending from the base class Exception.

 

 

try..except block

 

A try..except block looks like:

 

try

  // Code that may raise an exception

except

  on E: Exception do

    ShowMessage(E.Message);

end;

 

Delphi2Cpp converts this to:

 

  try

  {

  // Code that may raise an exception

  }

  catch(Exception& E)

  {

    ShowMessage(E.ReadPropertyMessage());

  }

 

 

try..finally block

 

The try..finally block ensures that cleanup code is executed regardless of whether an exception occurs:

 

 

try

// Code that may raise an exception

finally

// Always executed (e.g., resource cleanup)

end;

 

Delphi2Cpp uses a lambda expression (onLeavingScope) to simulate the Delphi behavior in C++:.

 

 

Custom exceptions

 

Custom exceptions are defined by inheriting from Exception:

 

type

  EMyError = class(Exception);

 

 

The simplified corresponding C++ definition is:

 

 

class EMyError : public Exception

{

public:

  EMyError(const String& Msg)

    : Exception(Msg) {}

 

  EMyError(const String& Msg, const System::ArrayOfConst& Args)

    : Exception(Msg, Args) {}

};

 

 

raise statement

 

Delphi exceptions can be raised using the raise keyword. For example:

 

procedure CheckName(name: string);

begin

  if Length(name) = 0 then

    raise EMyError.CreateFmt('Invalid name: ''%s''', [name]);

end;

 

function CreateName: string;

begin

  try

    // Build or compute name

    CheckName(Result);

  except

    on E: Exception do

    begin

      Result := 'Invalid name: ''Badname''';

      ShowMessage(E.Message);

    end;

  end;

end;

 

Following modern C++ best practices, Delphi2Cpp translates this to exceptions that are thrown by value and caught by reference:

 

void CheckName(String name)

{

  if (name.size() == 0)

    throw EMyError(L"Invalid name: '%s'", ArrayOfConst(name));

}

 

String CreateName()

{

  String result;

  try

  {

    // build name

    CheckName(result);

  }

  catch (Exception& E)

  {

    result = L"Invalid name: 'Badname'";

    ShowMessage(E.ReadPropertyMessage());

  }

  return result;

}



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content