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

C# try-catch处理异常

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

使用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处理异常” 的相关文章

C# 泛型委托

C# 泛型委托

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

C# 正则表达式(2)

// pattan = @"[^ahou]"; 表示匹配除ahou之外的字符,^在表示反义 string res4 = Regex.Replace(s, @"[^ahou]",&...

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

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

今天突然想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# 通过事件传递参数

C# 通过事件传递参数

20200622气死我了,一开始写的很详细,提交的时候因为长时间未操作提交失败了,今天懒得再写了,只把代码贴出来算了。事件发布相关类:public class ProEventArgs : EventArgs {    &nb...

C语言 异或运算符 ^

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