Global exception handling in c# (console application)

12,531

Handling exceptions globally is good for certain tasks only, such as logging errors or graceful exit of the application.

In all other cases, it is recommended that you handle the exception in the most relevant place. For example, if you make a web service call from your app and if the service is not available, you should handle that exception where you make the webservice call instead of catching it globally. This improves the readability of the code, and also it's not practical to do anything sensible at global level as you have very little information on where the exception originated. (Of course you have the stack trace, but its not readily available for programmatic manipulation)

However, you can add an application wide exception handler by attaching a handler to AppDomain.UnhandledException as also indicated in the comment by @Jesse

Share:
12,531
user1826831
Author by

user1826831

Updated on June 27, 2022

Comments

  • user1826831
    user1826831 almost 2 years

    Possible Duplicate:
    .NET Global exception handler in console application

    I've read a lot of things about global exception handling on stackoverflow, but I could not find anything refering to my topic properly. I wrote a console application that catches exceptions just in the methods they occur. No throw's at all. What I want to have is a global exception handling. I no the basic guidlines about exception handling, but got no idea beyond those basics. Imaginary there should be one class handling those exceptions (thrown by the methods from the different classes). I don't need any error-recording or error-reporting mechanisms yet. Just need the basics (patterns whatever...) to implement this global handling. Thanks for reading so far!

  • user1826831
    user1826831 over 11 years
    Thanks so far. The point is, I have a huge class, with almost thousand lines of code and almost every method needs a try/catch block bececause of socket-operations. I thought, it could maybe improve the readability if I use something like a global exception handler... Thats why I was asking. Furthermore, I thought, it would be a better programming style, to not catch the exceptions local.
  • BuddhiP
    BuddhiP over 11 years
    I think moment you got a 'thousand line' class you should know there is something wrong with it. :) You should try to adhere to Single Responsibility Principal, a class should deal with only one thing. I'd say you must break this class, ideal thing would be to create a generic class to handle socket calls, and handle exceptions inside that, and no. Global handling is not the correct style, local handling is the way to go.