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

C# try-catch处理异常

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

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

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

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# 与文件相关的几个类(1)

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

C# 与文件访问相关的常用的类:File类、Directory类、Path类、FileInfo类、DirectoryInfo类、FileSystemInfo类、FileSystemWatcher类以上几个类均在System.IO命名空间下。挨个说吧:File类:静态类,只有静态方法,用于移...

C# 抽象类与接口的比较

相同:都不能被实例化都包含未实现的方法派生类必须实现未实现的方法不同:抽象类可以包含抽象成员,也可以包含非抽象成员,即抽象类可以是完全实现的,也可以是部分实现的,或者是完全不实现的。接口更像是只包含抽象成员的抽象类,或者说接口内的成员都是未被实现的。一个类只能继承一个抽象类(当然其它类也一样),但是...