C# 异常捕获

文章目录

C# 异常捕获

捕获异常

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Test
    {
        int result;
        Test()
        {
            result = 0;
        }
        public void division(int num1,int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch(DivideByZeroException e)
            {
                Console.WriteLine("Exception caught:{0}", e);
            }
            finally
            {
                Console.WriteLine("Result:{0}", result);
            }
        }
        static void Main(string[] args)
        {
            Test t = new Test();
            t.division(23, 0);
            Console.ReadKey();
        }
    }

}

运行效果

自定义异常

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public class TempIsZeroException : ApplicationException
    {
        public TempIsZeroException(string message) : base(message)
        {
        }
    }
    public class Temperatrue
    {
        int temperature = 0;
        public void show()
        {
            if (temperature == 0)
            {
                throw (new TempIsZeroException("ZERO TEMPERATRUE FOUND"));
            }
            else
            {
                Console.WriteLine("Temperatrue:{0}", temperature);
            }
        }
    }
    class Test
    {
        int result;
        Test()
        {
            result = 0;
        }
        public void division(int num1,int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch(DivideByZeroException e)
            {
                Console.WriteLine("Exception caught:{0}", e);
            }
            finally
            {
                Console.WriteLine("Result:{0}", result);
            }
        }
        static void Main(string[] args)
        {
            Temperatrue t = new Temperatrue();

            try
            {
                t.show();
            }
            catch (TempIsZeroException e)
            {
                Console.WriteLine("TempIsZeroException:{0}", e.Message);
            }
            Console.ReadLine();
        }
    }

}

运行结果

抛出异常

csharp 复制代码
catch(Exception e)
{
   ...
   Throw e
}
相关推荐
码艺-Alimjan4 小时前
Web 网站打包桌面应用的另一种方式,超级简单(C# exe 33Kb)
开发语言·前端·c#
海天鹰5 小时前
C#入门:显示窗口
c#
淡海水5 小时前
16-02-C#常用数据结构源码-附录B-源码索引速查
unity·c#·游戏引擎·il2cpp
海天鹰6 小时前
C#入门:在cmd显示字符
c#
波力海苔夹心脆67517 小时前
C# 序列化与反序列化详解:System.Text.Json、Newtonsoft.Json、XmlSerializer 用法、特性选项与安全实践
经验分享·后端·c#·json·.net
小羊没烦恼!1 天前
在Scrum中实施敏捷建模
java·开发语言·windows·算法·c#
Lost of 程序猿1 天前
建造者模式实战:告别“十参数构造函数“的数据导出任务
后端·设计模式·c#·asp.net
mudtools1 天前
在.NET现有系统中快速集成飞书任务分配能力
后端·c#·.net
工具派1 天前
Word文档太大怎么拆分?段落结构与两种拆法的边界实测
开发语言·c#·word
潜龙95271 天前
需求文档一键变测试用例:手工用例智能生成平台
开发语言·c#