当前位置:首页 > 代码相关 > 正文内容

C# try-catch处理异常

admin4年前 (2020-03-23)代码相关2488

使用try-catch进行异常处理,下面是两个小例子:


两个例子中没有写finally语句

finally的作用是无论有无异常,finally下的语句都会执行。

//简单的处理异常
namespace _20200323
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = Console.ReadLine();
            string b = Console.ReadLine();
            Calculator cal = new Calculator();
            int ad = cal.Add(a, b);
            Console.WriteLine(ad);

        }

    }

    class Calculator
    {
        public int Add(string argu1, string argu2)
        {
            int a = 0;
            int b = 0;
            try
            {
                a = int.Parse(argu1);
                b = int.Parse(argu2);
            }

            catch
            {
                Console.WriteLine("输入数据有误");
            }

            int result = a + b;
            return result;

        }
    }
}
//精细的处理异常
namespace _20200323
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = Console.ReadLine();
            string b = Console.ReadLine();
            Calculator cal = new Calculator();
            int ad = cal.Add(a, b);
            Console.WriteLine(ad);

        }

    }

    class Calculator
    {
        public int Add(string argu1, string argu2)
        {
            int a = 0;
            int b = 0;
            try
            {
                a = int.Parse(argu1);
                b = int.Parse(argu2);
            }

            catch(ArgumentException)
            {
                Console.WriteLine("输入数据为null");
            }
            catch(FormatException)
            {
                Console.WriteLine("输入的不是数字");
            }
            catch(OverflowException)
            {
                Console.WriteLine("超出值的范围");
            }

            int result = a + b;
            return result;

        }
    }
}


扫描二维码推送至手机访问。

版权声明:本文由lovedm.club发布,如需转载请注明出处。

本文链接:http://lovedm.club/?id=20

标签: C#
分享给朋友:

“C# try-catch处理异常” 的相关文章

C#事件_Sample_3

事件的拥有者同时是事件的响应者using System; using System.Windows.Forms; /// <summary> /// 事件的拥有者同时是事件的响应者 /// </summary> na...

C# 泛型委托

C# 泛型委托

虽然没有必要,但是还是先看看自定义的泛型委托:namespace _20200402 {     class Program     {     &nb...

C# 与文件相关的几个类(2)

Directory类:静态类,主要处理文件目录。方法:CreateDirectory(String)在指定路径中创建所有目录和子目录,除非它们已经存在。返回值是一个DirectoryInfo对象Delete(String)从指定路径删除空目录。无返回值。Exists(String)确定给定路径是否引...

偶然想到的一个问题。。。

偶然想到的一个问题。。。

今天突然想C#中,用数组中的Max()方法和直接通过比较获取最大值的时间谁快,于是试了试:       static void Main(string[] args)   &nb...

C#(或者Java)反转数组

将原数组反转,如[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]反转后变为[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]因为数组是引用类型,所以直接在方法中处理即可,C#和Java写法一样,如下:      &nb...

C# 返回值是接口的方法

今天写PIE二次开发加载栅格数据的时候发现类中方法的返回值是接口,之前没怎么写过,在此记录一下。在例子中设计一个接口 ICalculate ,接口中有两个方法, Add() 和 Div() 分别为加法和减法的功能,均有两个参数,参数和返回值的类型都是int类型。设计一个名为Calculat...