throw(CError(ret)); //does formatmessage like you said.
You touched on very sensitive subject in contemporary programming. The
latest style (with .Net and all) is to throw exceptions left an right. It is
very OO, very modern etc. You example is perfect to illustrate why
exceptions are bad for error handling, or at least logical error handling:
1. m_hWnd is a member of your class, so if it is not a Window and it is not
NULL it indicates the sloppiness of the programmer, exception will only make
it worse. By throwing an exception you pass you problem to somebody else,
instead of fixing the problem. This case warrants assert but not the
exception.
2. CloseWindow seems to be destructor-ish kind of function, so there is a
good chance that additional clean up will follow, but it will be interrupted
by your throw.
3 Having m_cError is kind of strange, since the functionality is build into
the system (::SetLastError).This member serves no purpose, but being member
temporary variable.
4. Throwing 4 byte integer seems to be counter intuitive. Returning it as a
function result is cheaper and less destructive. If you really want to
throw create a class with appropriate implementation using ::FormatMessage
and all.
Over all I would encourage you to be super-conservative in usage of
exceptions, but I would like to emphasize that main stream programming today
moves the opposite direction. Check out samples form Microsoft and you will
find most abusive exception handling. Very good way to design exception
handling is to think if you want to be a user of your own class and if you
are willing to maintain it.
"mr.sir bossman" <mrsirbossman@discussions.microsoft.com> wrote in message
news:A3807ED7-3E97-4138-B948-6AD57880694E@microsoft.com...
I am writing a windows wrapper class and I am wondering if I should use
try-catch-throw in this function...Or should I just return the BOOL type
and
catch error at call with if()?
Any advice on this or a better way greatly appreciated. Thx ahead of time.
Note: Yes I've heard of MFC, ATL, WTL, etc and yes I know I should just
use
them.
<in windows wrapper class>
//windows handle
HWND m_hWnd;
//CError is just wrapper around DWORD
CError m_cError;
void CloseWindow() throw(CError)
{
if(!(::IsWindow(m_hWnd)))
{
m_cError.SetError(INVALID_HANDLE);
throw(m_cError);
}
if(!(::CloseWindow(m_hWnd)))
{
m_cError.SetError(0);
throw(::GetLastError());
}
}
</in windows wrapper class>