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
}
相关推荐
kylezhao201918 分钟前
C#上位机实现权限管理
开发语言·c#
工藤新一OL1 小时前
如何做COM组件
c#·visual studio
刘97531 小时前
【第23天】23c#今日小结
开发语言·c#
xiaowu0801 小时前
C# 把dll分别放在指定的文件夹的方法
开发语言·c#
自己的九又四分之三站台1 小时前
CSharp 编译器的历史(Roslyn 的诞生)
c#
MyBFuture2 小时前
C#表格与定时器实战技巧
开发语言·windows·c#·visual studio
feifeigo1232 小时前
基于C#实现即时通讯工具
开发语言·c#
程序猿多布2 小时前
C# 密封类、密封方法、密封属性、密封事件、密封索引器
c#
张人玉3 小时前
西门子 S7 PLC 通信 WPF 应用分析笔记
笔记·c#·wpf·plc
刘97533 小时前
【第22天】22c#今日小结
开发语言·c#