Simple explanation and use of C# | try-catch

1. The usual code

The usual code is executed line by line. If there is a problem with the execution of any line, an error will be reported or the operation will stop.

Second, the case

If you are a program:

get up at eight o'clock;

Go to KFC for breakfast;

have breakfast at KFC;

Subway;

work;

As a result, unfortunately, if KFC doesn’t open today, you will be stuck, and you won’t be able to implement it later. 

Sometimes, we will come across a part that I will not know whether it can be executed smoothly until it is executed, at that time and state.

Even sometimes, this part does not affect the main line of your program, for example, I can go to work without breakfast in the morning.

At this time, we need a method, we can try to implement it, and if it doesn't work, we can continue to do important things.

get up at eight o'clock;

Try going to KFC for breakfast; it's okay if you don't

Try KFC for breakfast; you can skip it

take the subway; take the subway hungry

go to work; go to work hungry

 3. Routine use of try-catch

            //八点起床;
            try
            {
                //去肯德基买早饭;
                //在肯德基吃早饭;
            }
            //如果try里面的代码出现意外 
            catch
            {
                //饿着就饿着
            }
            //坐地铁;
            //上班;

 Fourth, the specific use of catch

Catch can also distinguish the specific problem and correspond to the solution.

            //八点起床;
            try
            {
                //去肯德基买早饭;
                //在肯德基吃早饭;
            }
            //如果try里面的代码出现意外 
            catch(没找到肯德基)
            {
                //去找找别的早餐
                //买别的早餐
                //吃别的早餐
            }
            //坐地铁;
            //上班;

Guess you like

Origin blog.csdn.net/weixin_49427945/article/details/130337132
Recommended