About exception handling in C#

What is an exception? That is, errors will occur during program execution.

Then someone may ask, won't an error be reported when an error occurs in vs?

First of all, the errors that VS will report are basically grammatical errors, but VS will not prompt errors for logical errors. As long as it conforms to the grammar, vs will pass it before compilation. Secondly, in the process of writing programs, errors are inevitable, so what we need to write is more robust code to prevent and avoid program errors as much as possible.

In C#, try-catch-finally is commonly used for exception handling. The structure of the try-catch statement is as follows:

try{ ...; }

catch (...;) { ...;}

finally{ ...;}

Among them, catch can have multiple catch statements, and the finally statement is optional.

Place code that may cause errors and exceptions in try. Put the type of error in the catch and if an error occurs, how to deal with it or what prompt information, the code in finally will be executed regardless of whether the code is abnormal or not.

Let's use a small experiment to better understand exception handling.

Write the following experimental code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] a= { 1, 2, 3 };
            int m;
            try
            {
                m = a[3];
            }
            catch 
            {
                Console.WriteLine("变量m出现了数组访问过界的异常,执行了catch中的语句");
            }
            finally
            {
                Console.WriteLine("这是finally中的语句");

            }

            Console.WriteLine("这是try-catch-finally之外的语句");

            Console.ReadKey(true);
            }
        }
    }

The running results are as follows:

 After using the try-catch statement, since an exception does occur in try, the exception handling statement in catch will be executed, while the statement in finally will not be affected.

And if there is no try-catch statement, the running results are as follows:

 It can be found that the following statements will not be output at all, and the program will be interrupted.

Exception handling exercises:

 Write the code as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1
{
    class Program
    {
        static void Main(string[] args)
        {
            float a = 0, b = 0;
            label:   //定义书签label  方便goto跳转
            Console.WriteLine("请输入2个数字:");

            try
            {
               a = Convert.ToInt32(Console.ReadLine());
               b = Convert.ToInt32(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("您输入的不属于数字!");
                goto label;  //如果发生错误就让用户重新输入
            }
            float sum=a+b;
            Console.WriteLine("结果是:"+sum);

            Console.ReadKey(true);
            }
        }
    }

 

The result of the program running is as follows:

Finally, regarding finally: under what circumstances is it necessary to add finally?

Answer: For example, there may be exceptions when linking to the database, but when establishing a database connection channel, these resources will occupy memory. If a connection exception is found, the subsequent code to close the resource will not be executed, so you can put it in finally The code for these resource shutdowns.

All in all, using try-catch statements can prevent errors from occurring and enhance the robustness of the program.

Guess you like

Origin blog.csdn.net/qq_51196701/article/details/122967123