3. Implementation/COM & ActiveX

_com_error 클래스와 HRESULT 에러 처리

SSKK 2008. 10. 9. 23:49

#import 지시어가 생성하는 .TLI 파일의 메서드 구현 코드는 다음 예와 같이 HRESULT 값을 검사하여 실패한 경우에 _com_issue_error 또는 _com_issue_errorex 함수를 호출한다.

 

inline HRESULT IHello::sayHello(unsigned short * name, unsigned short ** message) {

HRESULT _hr = raw_sayHello(name, message);

if(FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));

return _hr;

}

 

l  _com_issue_error

단순히 HRESULT 값을 매개변수로 취하여 _com_error 데이터형의 예외를 던짐

l  _com_issue_errorex

HRESULT 값과 함께 인터페이스 포인터와 IID를 매개변수로 취하여 해당 인터페이스가 IErrorInfo 인터페이스를 지원하면 IErrorInfo 객체를 구하여 HRESULT와 함께 IErrorInfo 객체 정보를 포함시켜 _com_error 데이터형의 예외를 던짐

 

예외 처리

_com_ptr_t 스마트 포인터 클래스를 통하여 COM 객체를 사용할 때 발생하는 에러를 처리할 수 있다.

 

try {

IHelloPtr pIHello(__uuidof(Hello));

// ….

pIHello->sayHello(name, &message);

// …

}

catch (_com_error & e) {

cout << e.ErrorMessage << endl;

}

 

_com_error 예외 타입 클래스 멤버

 

l  ErrorMessage : 에러를 설명하는 const TCHAR * 리턴

l  Error : HRESULT , 즉 에러 코드값 리턴

l  Source : IErrorInfo::GetSource 멤버 함수의 호출 결과(_bstr_t) , 에러 소스 리턴

l  Description : IErrorInfo::GetDescription 멤버 함수의 호출 결과(_bstr_t) 리턴

만일 IErrorInfo가 저장되어 있지 않은 경우 빈 _bstr_t를 리턴하며, IErrorInfo 멤버 함수를 호출하는 동안 발생한 실패는 무시된다.

 

예외의 발생

 

다음 예제와 같이 _error_issue_error 함수를 사용

 

IHelloPtr {

HRESULT hr = p.CreateInstance(__uuidof(Hello));

if(FAILED(hr))

_com_issue_error(hr);

}

catch (_com_error & e) {

cout << e.ErrorMessage() << endl;

}

 

참고 : 전병선의 Component Development with Visual C++ & ATL