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

C# try-catch处理异常

admin6年前 (2020-03-23)代码相关3818

使用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发布,如需转载请注明出处。

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

标签: C#
分享给朋友:

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

递归计算1到x的和

递归真是个神奇的东西,当时学C的时候就没搞明白,学C#又遇到例子了。        public int SumXTo1(int x)     &n...

C#事件_Sample_1

事件模型的五个组成部分:1、事件的拥有者(event source,只能是对象或类)2、事件成员(event,成员)3、事件的响应者(event subscriber,对象)4、事件处理器(event handler,成员)--本质上是一个回调方法5、事件订阅--把事件...

C# 正则表达式(1)

C# 正则表达式(1)

用于匹配输入文本的模式string s = "this is a test!"; string res = Regex.Replace(s, "^",&nbs...

C、C++、C#交换变量

C、C++、C#交换变量

最近重新看了看C和C++,觉得有些地方挺有意思。作为一开始不管什么资料都会用来做例子的一个程序,交换变量。不管在哪,常用的int,float,double类型的变量都是值类型的,作为参数传到函数(方法)中时,其实是复制了一个值进去,也就是说通过函数是无法直接更改这些值的,只能通过一些间接的方法来更改...

C语言 异或运算符 ^

C语言中异或运算符^表示参见运算的二进制运算符相同为0,不同为1,如下:1 ^ 1 = 01 ^ 0 = 10 ^ 1 = 10 ^ 0 = 0下面举例说明∧运算符的应用:  (1)使特定位翻转  假设有01111010,想使其低4位翻转,即1变为0,0变为1。可以将它与00001111进行∧运算,...