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
}
相关推荐
-银雾鸢尾-21 小时前
C#中的反射关键类-Type
开发语言·c#
淡海水1 天前
15-07-YooAsset面试篇-Unity性能优化与内存管理
java·unity·面试·性能优化·c#·游戏引擎
hez20101 天前
.NET 11 Runtime Async 详解
c#·.net·.net core
猿长大人2 天前
C# | Serilog 新手入门
开发语言·c#·.net·log
在世修行2 天前
从零打造 C# 工业视觉检测系统(七):串口通信 SerialPort 封装与开发
开发语言·c#·modbus rtu·rs232/rs485
NoteStream2 天前
【C语言基础】分支和循环(上)
c语言·开发语言·c++·经验分享·笔记·算法·c#
lzhdim2 天前
C# 通过 Windows API 实现进程内存读写操作
开发语言·windows·c#
-银雾鸢尾-2 天前
C#中的预处理指令
开发语言·c#
dalong102 天前
Savitzky-Golay 的C# 实现
开发语言·kotlin·c#
猿长大人2 天前
C# | Autofac 新手指南:从零理解依赖注入与组件装配
c#·.net·di·依赖注入