[STAThread] static void Main() { Application.ThreadException+= new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.Run(new testExceptionHandler()); } private void Test_Click(object sender, System.EventArgs e) { throw new Exception(); } /// <summary> ///This method will handle all the exceptions thrown by application. ///and all other actions displaying, publishing it in log etc will be taken here /// </summary> private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { try { if(e.Exception is SqlException) { SqlException ex = (SqlException)e.Exception; if (ex.Number == 547) ErrorMessage("Record cannot be deleted or changed as it is being used somewhere else"); else if (ex.Number == 2627) ErrorMessage("Record cannot be saved, as another record with this key already exists"); else ErrorMessage(ex.Message.ToString()); } else ErrorMessage("System Error :"+e.Exception.Message.ToString()); //write in log //LogManager.publish(e.Exception.StackTrace.Substring(0,e.Exception.StackTrace.IndexOf("/n")-1), "", ""); } catch(Exception ex) { ErrorMessage("System Error: Reporting to log"); //LogManager.publish(ex.StackTrace, "", ""); } } public static string ErrorMessage(string msg) { return System.Windows.Forms.MessageBox.Show(msg, "Error",System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error).ToString(); }