C# 错误处理_异常处理

异常处理

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

namespace _003_错误处理_异常处理_ {
    class Program {
        static void Main(string[] args) {
            try
            {
                int[] myArray = {1, 2, 3, 4};
                int myEle = myArray[4];
            }
                //catch ( NullReferenceException e )//在这里我们虽然写了异常捕捉的程序,但是我们捕捉的类型不对,所以当发生别的类型的异常的时候,依然会终止程序的运行
                //{
                //    Console.WriteLine("发生了异常:IndexOutOfRangeException");
                //    Console.WriteLine("您访问数组的时候,下标越界了");
                //}
            catch//当我们不写catch的参数的时候,那么这个catch会捕捉出现的任何异常信息
            {
                Console.WriteLine("您访问数组的时候,下标越界了");
            }
            finally
            {
                Console.WriteLine("这里是finally里面执行的代码");
            }

            
            Console.WriteLine("test");
            Console.ReadKey();
        }
    }
}

输出

案例

让用户输入两个数字,用户可能会出入非数字类型,处理该异常,如果出现该异常就让用户重新输入,输出这两个数字的和

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

namespace _004_异常处理_案例2 {
    class Program {
        static void Main(string[] args)
        {
            int num1 = 0, num2 = 0;
            Console.WriteLine("请输入第一个数字");
            while (true)
            {
                try {
                    num1 = Convert.ToInt32(Console.ReadLine());//在try块中,如果有一行代码发生了异常,那么try块中剩余的代码就不会执行了
                    break;//如果上一条语句没有报异常,才会执行break
                } catch {
                    Console.WriteLine("您输入的不是一个整数,请重新输入");
                }
                //break;//把break放在这里的话,不管发布发生异常都会执行,因为try对异常进行了处理
            }
            Console.WriteLine("请输入第二个数字");
            while (true)
            {
                try {
                    num2 = Convert.ToInt32(Console.ReadLine());//在try块中,如果有一行代码发生了异常,那么try块中剩余的代码就不会执行了
                    break;//如果上一条语句没有报异常,才会执行break
                } catch {
                    Console.WriteLine("您输入的不是一个整数,请重新输入");
                }
                //break;//把break放在这里的话,不管发布发生异常都会执行,因为try对异常进行了处理
            }
            int sum = num1 + num2;
            Console.WriteLine(sum);
            Console.ReadKey();

        }
    }
}

发布了231 篇原创文章 · 获赞 8 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/cuijiahao/article/details/104206319