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

C# try-catch处理异常

admin5年前 (2020-03-23)代码相关3214

使用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# 属性,get,set使用

属性反映了状态,是对字段的自然扩展。下面的代码,有一个学生类,类中有年龄属性,通过get,set对年龄进行值的获取与设置,同时对年龄进行约束,使值控制在0-120之间,否则抛出异常信息。namespace _20200324_2 {     cl...

C# 正则表达式(1)

C# 正则表达式(1)

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

C# 正则表达式(2)

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

C# 测量运行时间

使用Stopwatch类进行运行时间的监测要使用 System.Diagnostics 命名空间方法表 4Reset()停止时间间隔测量,并将运行时间重置为零。Restart()停止时间间隔测量,将运行时间重置为零,然后开始测量运行时间。Start()开始或继续测量某个时间间隔的运行时间。...

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

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