Re: advice on best use of try catch throw
On Sun, 8 Apr 2007 03:20:01 -0700, mr.sir bossman
<mrsirbossman@discussions.microsoft.com> wrote:
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>
I'd be more inclined to use an assert(IsWindow()) rather than throw an
exception here and simply defer to the Windows API. (This is what MFC does,
and it's one of the things it gets right.) After all, if you're calling
CloseWindow with an invalid m_hWnd, it's your mistake. That is, m_hWnd can
be invalid at this point only if you never set it in the first place, or
you're using it after calling DestroyWindow, or you ignored a failed window
creation, etc. IOW, if it's a system error, you should have detected and
handled the error earlier, and if it's your fault, it's a bug you need to
fix. And what if the window does fail to minimize? How are you going to
handle that error? Are you going to pop up a message box to tell the user?
Consider the window dead from that point on? I don't think this rates
throwing an exception, and I'd just return BOOL like the Windows API. Heck,
it would probably be fine to continue to return void, because no one checks
the return codes of functions like this anyway. (For that to be taken as an
argument for throwing an exception, you'd need a really firm idea of how
the exception should be handled. And then you'd need to teach people that
every API wrapper you provide can throw exceptions, and watch as the amount
of exception-unsafe code they write rises dramatically anyway. Then you can
try to calculate whether or not you're solving more problems than you're
causing.)
--
Doug Harrison
Visual C++ MVP