0

I created a program that sends data between clients and when ever a runtime exception occurs, the whole program just exits.

I want to create a global catcher for all runtime exceptions so my program doesn't exit anytime a runtime exception occurs. When an exception occurs, the program exits and this message is printed:

Process finished with exit code -532,462,766.

This is a shortened view of my error stack:

Unhandled exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.IO.InvalidDataException: Found invalid data while decoding.
   at Game.Packet.PacketReader.ReadString(Int32 length) in PATH:line 53
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
--- End of stack trace from previous location where exception was thrown ---
   ...
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

I read some articles about how errors will bubble through so the first thing I tried was wrapping my main statement in program.cs but that didn't work neither. The next thing I tried was a solution I saw on another thread that said to use the delegates in AppDomain.CurrentDomain so I did and it didn't work either, the program exits. These were the delegates:

AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) => {
    Debug.WriteLine(eventArgs.ToString());
};

AppDomain.CurrentDomain.UnhandledException += (sender, exception) => {
    Debug.WriteLine(exception.ToString());
};

I came from Java and the program didn't exit after a runtime error; I am unsure why this is the case with c# and would appreciate tips and or suggestions. Thank you!

Edit: This is a Console Application

Euni
  • 11
  • 4
  • Please share the main program code and project type (console app? web app?). Caught exceptions don't make the program exit. – Athanasios Kataras Sep 19 '20 at 07:12
  • @AthanasiosKataras This occurs in a Console Application! The main statement just initializes all the data for caching. Errors can occur from anywhere, I need a more of a generic way of catching all unhandled exceptions so I could go back to handle them. Thanks! – Euni Sep 19 '20 at 07:16
  • You cannot handle unexpected exceptions. Your program state is no longer known and execution cannot proceed in any sort of safe way. The closest you could come to your goal is to put `try`/`catch` at the top of every thread, but some exceptions simply cannot be caught, and even the ones you can still leave you with the corrupted-state problem. – Peter Duniho Sep 19 '20 at 07:35

0 Answers0