Exception handling in C#(3 examples, with throw custom exception)

Lionsure 2020-08-25 Original by the website

No matter how well-designed the program is, it is inevitable that exceptions will not occur during the execution. If the exception is not handled well, it will affect the user's use, thereby affecting the user experience, and will eventually be abandoned by the user. Therefore, it is very important and necessary to handle the exception properly.

C# exception handling usually has two methods, one is to catch and handle exceptions in one method, and the other is to handle exceptions globally, that is, a software or website only catches exceptions in one public method, and saves the relevant exception information to an error Log file in order to correct the exception.

 

1. Local exception handling in C#

It is estimated that the program may go wrong in one method, you can use try{}catch{} to do local exception handling, you can throw exceptions, you can also pop up related prompts, the code is as follows:

/// <summary>
       /// C# throw exception when read file
       /// </summary>
       /// <param name="filePath">Path</param>

       private void ReadFileException(string filePath)
       {
              try
              {
                     StreamReader sr = new StreamReader(Server.MapPath(filePath));
                     string line = null;
                     while (line != null)
                     {
                            line = sr.ReadLine();
                            if (line != null)
                            Response.Write("<br />" + line);
                     }
              }
              catch (Exception ex)
              {
                     //Method 1
                     throw new Exception(ex.Message);

              //Method 2
                     throw new ArgumentNullException(ex.Message);

              //Method 3: C# throw custom exception
                     throw new Exception("Error reading file!");
              }
       }

Call: ReadFileException(@"G:\xq\test\error.txt";);

 

 

2. Global exception handling in C#

Websites and software(applications) have different global exception handling. The website only needs to catch the exception in the Global file, and the software catches it in the main() method of the program entry. The following takes the global catching exception of website as an example. The software example will be introduced in the next file.

/// <summary>
       /// Global exception handling in C#
       /// </summary>

       protected void Application_Error(object sender, EventArgs e)
       {
              Exception ex = Server.GetLastError().GetBaseException();
              SaveErrLog.AddLog(ex);//Use xml to save the error log and write your own program

       this.Server.ClearError();
              this.Response.Redirect("404 page");
       }

 

 

3. Special exception handling in C#

In some cases, when an exception occurs, it is not necessary to record the error message or pop up prompts, only to correct the error. For example, when turning pages, when the page number entered by the user exceeds the range or is not a number, only need to correct it to the last page or the first page. The code is as follows:

/// <summary>
       /// Special exception handling in C#
       /// </summary>
       /// <param name="pageNum">Page number</param>
       /// <returns>Integer page number</returns>

       private int SpecialException(string pageNum)
       {
              try
              {
                     return int.Parse(pageNum);
              }
              catch
              {
                     return 0;
              }
       }