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
}
相关推荐
William_cl2 小时前
C# ASP.NET MVC 数据验证实战:View 层双保险(Html.ValidationMessageFor + jQuery Validate)
后端·c#·asp.net·mvc
狮子不白3 小时前
C#WEB 防重复提交控制
开发语言·前端·程序人生·c#
Charles_go4 小时前
C#8、有哪些访问修饰符
java·前端·c#
yue0086 小时前
C# 求取整数的阶乘
java·开发语言·c#
黑咩狗夜.cm8 小时前
Aspose.word实现表格每页固定表头、最后一行填满整个页面
开发语言·c#·word
code bean8 小时前
【C#笔记】Newtonsoft.Json 中 `[JsonIgnore]` 的作用详解
笔记·c#·json
ccut 第一混8 小时前
用c# 制作一个扑克牌小游戏
开发语言·c#
IT老大哥9 小时前
局域网扫码枪/局域网二维码接收工具
c#·net
自由的好好干活10 小时前
C#桌面框架与Qt对比及选型(国产操作系统开发视角)
开发语言·qt·c#
The Sheep 202311 小时前
MicroService(Redis)
数据库·redis·c#