code_junkie

.NET - What's the best way to implement a “catch all exceptions handler”

Nov 11th, 2011
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. class Program
  2. {
  3. void Run()
  4. {
  5. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  6.  
  7. Console.WriteLine("Press enter to exit.");
  8.  
  9. do
  10. {
  11. (new Thread(delegate()
  12. {
  13. throw new ArgumentException("ha-ha");
  14. })).Start();
  15.  
  16. } while (Console.ReadLine().Trim().ToLowerInvariant() == "x");
  17.  
  18.  
  19. Console.WriteLine("last good-bye");
  20. }
  21.  
  22. int r = 0;
  23.  
  24. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  25. {
  26. Interlocked.Increment(ref r);
  27. Console.WriteLine("handled. {0}", r);
  28. Console.WriteLine("Terminating " + e.IsTerminating.ToString());
  29.  
  30. Thread.CurrentThread.IsBackground = true;
  31. Thread.CurrentThread.Name = "Dead thread";
  32.  
  33. while (true)
  34. Thread.Sleep(TimeSpan.FromHours(1));
  35. //Process.GetCurrentProcess().Kill();
  36. }
  37.  
  38. static void Main(string[] args)
  39. {
  40. Console.WriteLine("...");
  41. (new Program()).Run();
  42. }
  43. }
  44.  
  45. try
  46. {
  47. CallTheCodeThatMightThrowException()
  48. }
  49. catch (Exception ex)
  50. {
  51. System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();
  52. Utils.ErrorHandler.Trap ( ref objUser, st, ex );
  53. } //eof catch
  54.  
  55. using System;
  56. using log4net; //or another logging platform
  57.  
  58. namespace GenApp.Utils
  59. {
  60. public class ErrorHandler
  61. {
  62. public static void Trap ( Bo.User objUser, ILog logger, System.Diagnostics.StackTrace st, Exception ex )
  63. {
  64. if (ex is NullReferenceException)
  65. {
  66. //do stuff for this ex type
  67. } //eof if
  68.  
  69. if (ex is System.InvalidOperationException)
  70. {
  71. //do stuff for this ex type
  72. } //eof if
  73.  
  74. if (ex is System.IndexOutOfRangeException)
  75. {
  76. //do stuff for this ex type
  77. } //eof if
  78.  
  79. if (ex is System.Data.SqlClient.SqlException)
  80. {
  81. //do stuff for this ex type
  82. } //eof if
  83.  
  84. if (ex is System.FormatException)
  85. {
  86. //do stuff for this ex type
  87. } //eof if
  88.  
  89. if (ex is Exception)
  90. {
  91. //do stuff for this ex type
  92. } //eof catch
  93.  
  94. } //eof method
  95.  
  96. }//eof class
  97. } //eof namesp
  98.  
  99. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
  100.  
  101. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Add Comment
Please, Sign In to add comment