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
}
相关推荐
游乐码5 小时前
c#万物之父装箱拆箱
开发语言·c#
GIS程序猿5 小时前
批量出图工具,如何使用C#实现动态文本
开发语言·arcgis·c#·arcgis插件·gis二次开发
量子物理学5 小时前
三、C#高级进阶语法——特性(Attribute)
java·算法·c#
量子物理学6 小时前
四、C#高级进阶语法——委托(Delegate)
开发语言·c#
bepeater12347 小时前
Laravel9.X核心特性全面解析
c语言·c++·c#·php
lpfasd1238 小时前
Markdown 导出 Word 文档技术方案
开发语言·c#·word
m5655bj9 小时前
通过 C# 将 PPT 文档转换为 HTML 格式
c#·html·powerpoint
未来之窗软件服务9 小时前
AI人工智能(十五)C# AI的智障行为http服务—东方仙盟练气期
开发语言·http·c#
缺点内向9 小时前
C#中如何创建目录(TOC):使用Spire.Doc for .NET实现Word TOC自动化
c#·自动化·word·.net
2301_816997889 小时前
Word 创建打开与保存文档
c#·word·xhtml