Skip to content

Commit

Permalink
Implement Exception Handling
Browse files Browse the repository at this point in the history
This implements Exception Handling: by using try-catch blocks to handle exceptions that might occur during the execution of dwm-win32. This allows us to call `unmanage()` on all windows before crashing, and thus not losing any programs.

The `__try` block contains the main program code. If an unhandled exception occurs anywhere in this block, control immediately transfers to the `__except` block. The `cleanupOnException` function is then called to unmanage all windows before the program crashes.
  • Loading branch information
adham-elaraby authored Dec 21, 2023
1 parent 68cdaa4 commit 56c33a1
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/dwm-win32.c
Original file line number Diff line number Diff line change
Expand Up @@ -1649,6 +1649,14 @@ forcearrange(const Arg *arg) {
arrange();
}

//catches unhandled exceptions and performs necessary cleanup before a crash, you can use Structured Exception Handling (SEH) in Windows
// This function will be called when an exception occurs
void cleanupOnException() {
Client *c;
for (c = clients; c; c = c->next) {
unmanage(c);
}
}

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd) {
SetProcessDPIAware();
Expand All @@ -1662,14 +1670,23 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLi
die(L"dwm-win32 already running");

lua_State *L = luaL_newstate();
setup(L, hInstance);

// the __try block contains the main program code. If an unhandled exception occurs anywhere in this block, control immediately transfers to the __except block. The cleanupOnException function is then called to unmanage all windows before the program crashes.
// Establish an exception handler
__try {
setup(L, hInstance);

while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}

while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
cleanup(L);
}
// Catch any unhandled exceptions
__except(EXCEPTION_EXECUTE_HANDLER) {
cleanupOnException();
}

cleanup(L);

return msg.wParam;
}

0 comments on commit 56c33a1

Please sign in to comment.