栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

c# 异常(exception)

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c# 异常(exception)

捕获并处理
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = Console.ReadLine();
            string str2 = Console.ReadLine();
            int result = Add(str1, str2);
            Console.WriteLine(result);
        }

        static int Add(string str1, string str2)
        {
            int n1 = 0;
            int n2 = 0;
            bool hasError = false;
            try
            {
                n1 = int.Parse(str1);
                n2 = int.Parse(str2);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("ArgumentException");
                Console.WriteLine(e.Message);
                hasError = true;
            }
            catch (FormatException e)
            {
                Console.WriteLine("FormatException");
                Console.WriteLine(e.Message);
                hasError = true;
            }
            catch (OverflowException e)
            {
                Console.WriteLine("OverflowException");
                Console.WriteLine(e.Message);
                hasError = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("exception");
                hasError = true;
            }
            finally
            {
                if (hasError)
                {
                    Console.WriteLine("程序发生异常");
                }
            }

            return n1 + n2;
        }
    }
}
抛出异常
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = Console.ReadLine();
            string str2 = Console.ReadLine();

            int result = 0;
            try
            {
                result = Add(str1, str2);
            }
            catch (FormatException)
            {
                Console.WriteLine("格式异常");
            }

            Console.WriteLine(result);
        }

        static int Add(string str1, string str2)
        {
            int n1 = 0;
            int n2 = 0;

            try
            {
                n1 = int.Parse(str1);
                n2 = int.Parse(str2);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (FormatException e)
            {
                // throw e 也可以,下面是简写
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine("exception");
            }

            return n1 + n2;
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906809.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号