ExceptProc is not called on Windows

I'm currently trying to create an Exception handler built into my Windows service, which in an unhandled exception sends a message to another program. I built a method and received a message, but it seems that every time my program throws an error, (I have a call call in the code to force it.) Windows catches it, and the handler is not called. Can someone explain what I'm doing wrong?

Simplified code to explain:

procedure unhandled(); begin raise Exception.Create('Unhandled'); end; procedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer); begin WriteLn('Display: ' + Exception(ExceptObject).Message); //send Message Here end; 

I call this code to run it:

 WriteLn('Starting'); ExceptProc := @ExceptionHandler; unhandled(); 

I expect the output to be as follows:

Launch
Display: Raw

but all he does is display:

Launch

Then the windows return the command line after about 5 seconds.

Why is the handler called incorrectly?

PS I tested these tests in a console application for testing.

EDIT:

Here is some more info:

Apparently, when you have ExceptProc assigned, your program should not throw a common 211 runtime error. I assume this is what Windows catches. From what I see, my program throws this runtime error, and I cannot get ErrorProc to catch it.

+4
source share
2 answers

You do not need a call to SetErrorMode () :

 SetErrorMode(SEM_NOGPFAULTERRORBOX); 

This is to prevent the OS from having an unhandled exception filter display a dialog box / display a debug attach dialog box. Here's a complete sample that behaves as expected on my machine:

 {$apptype console} uses Windows, SysUtils; procedure unhandled(); begin raise Exception.Create('Unhandled'); end; procedure ExceptionHandler(ExceptObject: TObject; ExceptAddr: Pointer); begin Writeln('here'); WriteLn('Display: ' + Exception(ExceptObject).Message); Flush(Output); Halt(1); end; procedure Go; begin unhandled; end; begin ExceptProc := @ExceptionHandler; SetErrorMode(SEM_NOGPFAULTERRORBOX); Go; end. 

Note that the SetErrorMode () effect is global for all threads in the running process.

+8
source

Interesting.

A custom exception handler is called if you run the application in the Delphi IDE (tested since 2007), but not if you started it from the command line.

Another interesting thing - I changed the main program code to

 begin WriteLn('Starting'); try ExceptProc := @ExceptionHandler; Unhandled; finally Readln; end; end. 

and noticed that the exception message is only displayed AFTER I press the Enter key (to get some input in Readln). Therefore, your handler is not called when an exception occurs, but when it is thrown (in an implicit attempt, except that it wraps all your code). Make sense.

There must be something with this implicit attempt .. moreover, but I don’t have the Delphi debugger on this machine and can’t dig further. Maybe someone else knows the answer ...

0
source

All Articles