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
}
相关推荐
烛阴34 分钟前
C# 正则表达式:量词与锚点——从“.*”到精确匹配
前端·正则表达式·c#
云中飞鸿2 小时前
值类型、引用类型
c#
c#上位机5 小时前
halcon窗口显示文字
图像处理·c#·halcon
kingwebo'sZone5 小时前
Datagridview 显示当前选中行
c#
时光追逐者6 小时前
一个基于 .NET 开源、功能强大的分布式微服务开发框架
分布式·微服务·开源·c#·.net·.net core
Poetinthedusk6 小时前
设计模式-命令模式
windows·设计模式·c#·wpf·命令模式
csdn_aspnet9 小时前
C# 电子签名及文档存储
javascript·c#
武藤一雄11 小时前
一款基于WPF开发的BEJSON转换工具
windows·c#·json·wpf
秦苒&12 小时前
【C语言】详解数据类型和变量(二):三种操作符(算数、赋值、单目)及printf
c语言·开发语言·c++·c#
张人玉12 小时前
c#常用的类
服务器·数据库·c#