Catch all exceptions in the application with only one attempt

Is there a way to catch all exceptions in an application in Main () with a single try-catch regardless of threads and applications in the application?

In other words, I just want to use a single try-catch to log all errors in my application instead of using multiple catch attempts in different places.

Please any ideas or code fragments ...

Edit: I am using a console application and a Windows service.

+4
source share
3 answers

Is there a way to catch all exceptions in a Main () application with one try-catch regardless of threads and applications within the application

No, exceptions relate to the thread, so if you are not doing something to throw exceptions from other threads into your main thread, there is no way to catch exceptions from other threads.

eg. if you are calling an asynchronous delegate call, you need to call EndInvoke to get any exception back to the calling thread. If you are just starting a thread and are not doing anything to handle or marshal the exception, an unhandled exception will cause the application to terminate.

+2
source

I doubt it would be helpful to have a common place for reporting errors.

What do you want to achieve - code reduction?

Image is an InvalidFileFormatException exception that may occur in your application when you try to open a file whose format is not as expected. A global exception handler might register this. Then your log file will read something like:

[Yesterday...] The file format is invalid: InvalidFileFormatException. StackTrace: ... 

But what do you get from this information? Well, I admit that if there is only one call in your application that could throw this exception, everything will be okay. But what if there are multiple calls to the same method or if other called methods throw the same exception?

You should rely on a detailed exception message, but unfortunately, when it comes to exceptions thrown in Runtime, you cannot influence the messages. It would not be better to have something like

 string fileName = @"C:\Users\stackoverflow\Documents\file.frk"; try { FreakingObject fo = freakingObjectConverter.ReadFromFile(fileName, FreakFormat.AutoDetect); } catch (InvalidFileFormatException iffe) { MyLogger.LogError("File " + fileName + " had an invalid format:", iffe); } 

In this example, you at least get information about the malformatted file. You can easily create more complex examples (HttpRequest, etc.), where you can add very useful information to your journal, if only you knew about the context in which the Exception was added.

A small hint of try-catch around Application.Run(...) : keep in mind that whenever you reach the catch block, your application terminates if you do not recreate the main form or do nothing.

+1
source

Source: https://habr.com/ru/post/1315884/


All Articles