@TRY_BEGIN MACRO Handler pushad mov push push mov esi, offset Handler esi dword ptr fs:[0] dword ptr fs:[0], esp ;;Save Current State ;;Address of New Exception Handler ;;Save Old Exception Handler ;;Install New Handler ENDM @TRY_EXCEPT MACRO Handler Handler: jmp mov pop add popad NoException&Handler esp, [esp + 8] dword ptr fs:[0] esp, 4 ;;No Exception Occured, so jump over ;;Exception Occured, Get old ESP ;;Restore Old Exception Handler ;;ESP value before SEH was set ;;Restore Old State ENDM @TRY_END MACRO Handler NoException&Handler: ExceptionHandled&Handler: jmp pop add ExceptionHandled&Handler dword ptr fs:[0] esp, 32 + 4 ;;Exception was handled by @TRY_EXCEPT ;;No Exception Occured ;;Restore Old Exception Handler ;;ESP value before SEH was set. 32 for pushad and ... ;;...4 for push offset Handler. (No Restore State) ;;Exception has been handled, or no exception occured ENDM @TRY_BEGIN Name_Of_Handler ; @TRY_EXCEPT Name_Of_Handler ; @TRY_END Name_Of_Handler ; ;Structured Exception Handling in Assembly ;(c) 2000, Rohitab Batra ;software@rohitab.com ;This Code was downloaded from http://www.rohitab.com/ ; ;To Compile this program, you need the 32-bit version of Turbo Assembler ; ;TASM32 /ml SEH ;TLINK32 SEH,SEH,,IMPORT32.LIB .386p .model flat ,stdcall EXTRN ExitProcess:PROC EXTRN MessageBoxA:PROC ;Define the @TRY_BEGIN, @TRY_EXCEPT and @TRY_END Macros Here .data szCaption szException szNoException db db db db 'SEH in Assembly', 0 'Exception has been handled !!', 0dh, 0ah 'Press OK to terminate gracefully', 0 'No Exception occured', 0 .code WinMain: @TRY_BEGIN Zero_Address_Access mov mov ebx, 0 [ebx], ebx ;Prepare to write to address 0 ;Write to address 0 (Access Violation) ;Comment the above line if to remove the exception @TRY_EXCEPT Zero_Address_Access ;This code will get executed if an exception occurs call jmp MessageBoxA, 0, offset szException, offset szCaption, 0 ExitProgram @TRY_END Zero_Address_Access ;Normal execution path ExitProgram: call MessageBoxA, 0, offset szNoException, offset szCaption, 0 call ExitProcess, 0 ;Terminate END WinMain