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
}
相关推荐
爱吃小胖橘1 小时前
Unity资源加载模块全解析
开发语言·unity·c#·游戏引擎
时光追逐者2 小时前
全面的 C#/.NET 图表构建解决方案,助力快速实现图表开发需求!
微软·c#·.net·.net core·图表
m5655bj2 小时前
通过 C# 在 Word 文档中添加文字或图片水印
c#·word·visual studio
无盐海13 小时前
泛型的协变(Covariance)和逆变(Contravariance)
c#
MintYouth13 小时前
【加精】C# XML差异对比 (直接用)
xml·windows·c#
刀一寸13 小时前
C# WebAPI下Swagger的配置
ui·c#
大飞pkz14 小时前
【算法】排序算法汇总1
开发语言·数据结构·算法·c#·排序算法
儒雅永缘14 小时前
VBA实现word文档批量转PDF文件
pdf·c#·word
张人玉16 小时前
WPF 控件速查 PDF 笔记(可直接落地版)(带图片)
大数据·microsoft·ui·c#·wpf
葛小白116 小时前
Winform控件:Combobox
前端·ui·c#·combobox