A simple unified exception handling method. An exception occurs at the bottom of the system, and a record file is written. The bottom layer of the system catches the bottom layer and displays prompt information.
/// <summary> /// Custom exception class /// </summary> public static class ExceptionExtension { /// <summary> /// User-defined error message /// </summary> public static string ErrorMessage { get; set; } /// <summary> /// Write exception log /// </summary> /// <param name="ex"></param> /// <param name="Message">User-defined error message</param> public static void WriterExceptionLog(Exception ex, string Message = "") { string filePath = (@"\bin\Debug", "") + @"\ErrorLog"; if (!(filePath)) { (filePath); } string fileName = filePath + @"\"; StringBuilder errorInfo = new StringBuilder(); ($"*******Time of exception occurrence:{}*******\n"); (" Exception type: {0} \n", ); //(" Exception instance that causes the current exception: {0} \n", ); (" The name of the application or object that caused the exception: {0} \n", ); (" Methods to raise exceptions: {0} \n", ); (" Exception stack information: {0} \n", ); (" Exception message: {0} \n", ); (" System Information: {0} \n", Message); ErrorMessage += Message; try { if ((fileName)) { using (StreamWriter tw = (fileName)) { (()); } } else { TextWriter tw = new StreamWriter(fileName); (()); ();// Force output of the buffer data and clear the buffer ();//Close the data flow tw = null; } } catch (Exception) { (); } } } }
It's relatively simple, this class only defines one property and one method. The specific use is as follows: When an exception is found at the bottom of the system (such as the data access layer or the business logic layer), the exception information is recorded and the exception is thrown. For example:
//Background processingtry { //Exception operation may occur} catch (Exception ex) { string strSlq = ""; (ex, "Exception occurred while querying records. SQL statement is:" + strSlq); throw;//Top an exception upward} finally { //Cleaning}
The user interaction layer captures the underlying exception and displays prompt information. For example:
//user interface try { //Exception may occur when calling the underlying layer } catch (Exception) { //(, "System Exception Error", , ); } finally { //Cleaning }
This is the end of this article about C# WINFORM custom exception handling methods. For more related contents of C# WINFORM exception handling methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!