본문 바로가기
Delphi/Delphi란?

Delphi OOP와 C++과의 차이 [5]

by MonoSoft 2021. 4. 30.
728x90
반응형

Delphi OOP와 C++과의 차이 [5]

Exception Handling

==================

C++과 델파이에서의 예외처리를 비교하기 위해서 13월과같이 유효하지않은

입력을 했을때의 Exception Handling을 처리하는 방법을 살펴보자.

 

컴파일러는 볼랜드 C++ 4.5 를 이용했다.

 

 

#include

#include

 

// 유효하지않은 월 입력의 에러코드

#define ErrorCodeInvalidMonth 100

 

// 예외 에러코드핸들링을 위한 크래스 선언

class Exception

{

private:

int m_ErrorCode;

public:

Exception(int ErrorCode) { m_ErrorCode = ErrorCode; }

int GetErrorCode() { return m_ErrorCode; }

};

 

// 예외처리를 테스트하기위한 시험용 크래스 선언

class MyClass

{

private:

int m_Month;

public:

MyClass() {}

void SetMonth(const int Month);

};

 

void MyClass::SetMonth(const int Month)

{

if(Month >= 1 && Month <= 12) m_Month = Month;

else

throw Exception(ErrorCodeInvalidMonth);

}

 

void main()

{

MyClass myobject;

try

{

// 예외처리 테스트를 위해 유효하지않은 13월을 입력

myobject.SetMonth(13);

}

catch(Exception E)

{

printf("Exception! : %d\n",E.GetErrorCode());

}

}

 

 

다음은 위의 C++ 예외 처리를 델파이로 구현해보자.

 

원래 델파이에서 코멘트는 '{'와 '}' 사이에 넣도록되있지만 편이상 지금

까지의 강좌에서는 C++의 코멘트 기호('//') 를 사용했다.'

 

델파이에서 프로젝트를 오픈한뒤, 오브젝트인스펙터 창에서 OnMouseDown

이벤트를 생성한다. 그런후 아래와같이되도록 코드를 입력한다.

 

Environment Option에서 Break On Exception을 셋팅하지않고서 컴파일 &

실행하도록한다.

 

 

unit Unit1;

 

interface

 

uses

SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,

Forms, Dialogs;

 

// SysUtils 유닛은 Exception 크래스를 제공한다.

type

MyException = class( Exception )

end;

 

type

MyClass = class( TObject )

private

m_Month: Integer;

public

constructor Create; // 생성자

destructor Destroy; // 소멸자

procedure SetMonth(const Month: Integer);

end;

 

 

type

TForm1 = class(TForm)

procedure FormMouseDown(Sender: TObject; Button: TMouseButton;

Shift: TShiftState; X, Y: Integer);

private

{ Private declarations }

public

{ Public declarations }

end;

 

var

Form1: TForm1;

 

implementation

 

{$R *.DFM}

 

constructor MyClass.Create;

begin

inherited Create; // 선조 TObject 객체의 생성자 호출

end;

 

destructor MyClass.Destroy;

begin

inherited Destroy; // 선조 TObject 객체의 소멸자 호출

end;

 

// MyClass 객체의 Method

procedure MyClass.SetMonth(const Month: Integer);

begin

if ( Month >= 1) and (Month <=12 )then

m_Month := Month

else

raise MyException.Create('Error: Invalid Month Input');

end;

 

// 이벤트 핸들러 정의

procedure TForm1.FormMouseDown(Sender: TObject; Btton: TMouseButton;

Shift: TShiftState; X, Y: Integer);

var

myobject: MyClass; // 델파이에서 크래스객체는 레퍼런스타입이다.

 

begin

myobject := MyClass.Create;

 

try

// Exception Handling을 테스트하기 위해서 의도적으로 유효하지않은

// 월을 입력

myobject.SetMonth(13);

 

except

on E : MyException do begin

MessageDlg('Exception! '+ E.Message,mtError,[mbOK],0);

end

end;

 

myobject.Destroy;

end;

 

end.

 

 

 

소스중..

on E : MyException 에서 'E'는 다음과 같이 SysUtils 유닛에 선언되어있

는 Exception 객체의 인스턴스를 참조하기위한 temporary로 사용된다.

 

Exception = class(TObject)

private

FMessage: PString;

FHelpContext: Longint;

function GetMessage: string;

procedure SetMessage(const Value: string);

public

constructor Create(const Msg: string);

constructor CreateFmt(const Msg: string;

const Args: array of const);

constructor CreateRes(Ident: Word);

constructor CreateResFmt(Ident: Word; const Args: array of const);

constructor CreateHelp(const Msg: string; AHelpContext: Longint);

constructor CreateFmtHelp(const Msg: string;

const Args: array of const;

AHelpContext: Longint);

constructor CreateResHelp(Ident: Word; AHelpContext: Longint);

constructor CreateResFmtHelp(Ident: Word;

const Args: array of const;

AHelpContext: Longint);

destructor Destroy; override;

property HelpContext: Longint

property Message: string;

property MessagePtr: PString;

end;

 

지금까지 델파이 OOP와 C++ 과의 주요 차이 부분에 대한것을 알아보았다.

C++만 사용하다가 파스칼 OOP 코드를 사용하는 델파이의 사용이 처음에는

거부감이 있었지만, 툴이 상당히 직관적인 비쥬얼환경이었고 OOP도 C++과

유사해서 쉽게 델파이 환경에 접근할 수 있었다.

 

강좌에 관심을 보여준 분들께 고마움을 표시하면서 마칩니다.

728x90
반응형

'Delphi > Delphi란?' 카테고리의 다른 글

델파이 객체지향이란?(2)  (2) 2023.06.12
델파이 객체지향이란?  (0) 2023.05.31
Delphi OOP와 C++과의 차이 [3]  (0) 2021.04.28
Delphi OOP와 C++과의 차이 [1]  (0) 2021.04.27
Delphi란...{6}  (0) 2021.04.26

댓글