I'm testing the program, I can’t write everywhere try... except . Is it possible to somehow display a message to the user like "Emergency shutdown of the program in case of emergency closing of the program, please remember your last actions"?

    1 answer 1

    If you want to catch all unhandled exceptions in your application, subscribe to AppDomain.UnhandledException

     [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)] public static void TestSomeException() { AppDomain domain = AppDomain.CurrentDomain; domain.UnhandledException += new UnhandledExceptionEventHandler(SomeExceptionHandler); throw new Exception("Тестовое исключение"); } static void SomeExceptionHandler(object sender, UnhandledExceptionEventArgs args) { Exception e = (Exception) args.ExceptionObject; // TODO: Обработать исключение } public static void Main() { TestSomeException(); } 
    • one
      And can you be more specific for the inexperienced? Where to write [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)] ? And I probably will not handle the error, but simply close the application after the messagebox, but this.close does not work in static. classroom. Where can I write this? - Rakzin Roman
    • The attribute [i.e. the fact that in square brackets] should be attributed to the method that will establish the subscription to the event. About this.Close () - I suggest instead using, for example, Application.Exit (). - Maxim Kamalov