From 58d30975f0d46dc7812b7266c3c2c823695503e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Ankarstr=C3=B6m?= Date: Sun, 31 Jul 2022 00:38:17 +0200 Subject: Simplify exception handling. --- c/common.cpp | 8 ++++++++ c/common.h | 1 + c/main.cpp | 36 +++++++++++++++++------------------- 3 files changed, 26 insertions(+), 19 deletions(-) diff --git a/c/common.cpp b/c/common.cpp index 77d669c..7ce1372 100644 --- a/c/common.cpp +++ b/c/common.cpp @@ -55,6 +55,14 @@ wstring_owner WsoFromSz(const char* const sz, const int iCp) return wsz; } +wstring_owner WsoCopy(const wchar_t* const src) +{ + const int cb = wcslen(src)+1; + wchar_t* dst = new wchar_t[cb]; + memcpy(dst, src, cb*sizeof(wchar_t)); + return dst; +} + /* Win32Error: Exception for Windows API errors. */ Win32Error::Win32Error() : dwErr(GetLastError()) {} diff --git a/c/common.h b/c/common.h index 8e850ed..e63095b 100644 --- a/c/common.h +++ b/c/common.h @@ -28,6 +28,7 @@ struct wstring_owner wstring_owner WsoFromSz(const char* sz, int iCp = CP_UTF8); int EBMessageBox(const wchar_t* wszText, const wchar_t* wszCaption, unsigned uType); +wstring_owner WsoCopy(const wchar_t* wsz); struct Win32Error : public std::exception { diff --git a/c/main.cpp b/c/main.cpp index 144d151..7af5a0b 100644 --- a/c/main.cpp +++ b/c/main.cpp @@ -44,32 +44,30 @@ static void WaitFor(const char*, const char*); static INT_PTR CALLBACK AboutDlgProc(HWND, UINT, WPARAM, LPARAM); static void UpdateTheme(); -void TerminateMsg(const wchar_t* wsz1, const wchar_t* wsz2) noexcept -{ - wchar_t wsz[256] = {0}; - if (wsz2) - wszf(wsz, L"Episode Browser was terminated due to %s: %s", wsz1, wsz2); - else - wszf(wsz, L"Episode Browser was terminated due to %s.", wsz1); - MessageBox(g_hWnd, wsz, L"Fatal Error", MB_ICONERROR); -} - void OnTerminate() noexcept { + const wchar_t* wszWhat = L"an exception"; + wstring_owner wsoWhy; + try { std::rethrow_exception(std::current_exception()); } catch (const term_t& t) { - if (auto wso = PlString(t)) - TerminateMsg(L"a Prolog exception", wso.p); - else - TerminateMsg(L"a Prolog exception", NULL); + wszWhat = L"a Prolog exception"; + try { wsoWhy = PlString(t); } catch (...) {} } catch (const Win32Error& e) { - TerminateMsg(L"a Windows error", e.WhatW()); + wszWhat = L"a Windows error"; + try { wsoWhy = WsoCopy(e.WhatW()); } catch (...) {} } catch (const std::exception& e) { - TerminateMsg(L"an exception", WsoFromSz(e.what()).p); - } catch (...) { - TerminateMsg(L"an exception", NULL); - } + try { wsoWhy = WsoFromSz(e.what()); } catch (...) {} + } catch (...) {} + + wchar_t wsz[256] = {0}; + if (wsoWhy) + wszf(wsz, L"Episode Browser was terminated due to %s: %s", wszWhat, wsoWhy.p); + else + wszf(wsz, L"Episode Browser was terminated due to %s.", wszWhat); + + MessageBox(g_hWnd, wsz, L"Fatal Error", MB_ICONERROR); _Exit(1); } -- cgit v1.2.3