c#异常处理

What an exception is?

有什么例外?

An exception is a runtime error; that means an abnormal situation which is created at run time and the program doesn’t execute successfully. Due to the exceptions, our program gets crash.

异常是运行时错误; 这意味着在运行时创建了异常情况,程序无法成功执行。 由于这些异常,我们的程序会崩溃。

There are following common exceptions are occurred during program:

在编程过程中发生以下常见异常:

  • Divide by Zero

    除以零

  • File not found

    文件未找到

  • Array Index out of bound

    数组索引超出范围

  • Null reference exception

    空引用异常

  • Invalid cast exception

    无效的强制转换例外

  • Arithmetic exception

    算术异常

  • Overflow exception

    溢出异常

  • Out of memory exception etc.

    内存不足异常等

Here is an example / program, that will generate exception

这是一个示例/程序,将产生异常

using System;
class Program
{static void Main()
{int number1 = 0;
int number2 = 0;
int result  = 0;
Console.WriteLine("Enter Number : ");
number1 = int.Parse(Console.ReadLine());
result = number1 / number2;
Console.WriteLine("Result : " + result);
}
}

When we compile above program it does not produce any error. Compilation result will be like this,

当我们编译以上程序时,它不会产生任何错误。 编译结果将是这样,

------ Build started: Project: ConsoleApplication1, Configuration: Debug x86 ------
ConsoleApplication1 ->C:\Users\Arvind\Documents\Visual Studio 2010\Projects\ihelp\
ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

And, when we execute the program then it produces an exception like this, (in the program, we are trying to divide a number by 0).

而且,当我们执行程序时,它会产生这样的异常(在程序中,我们试图将数字除以0)。

The above program generates "Divide by Zero exception" and the program gets crashed. Because variable number1 is divided by number2 and output stored in the result variable. Where, the value of number2 is 0, thus, "divide by zero exception" occurred.

上面的程序生成“被零除的异常” ,该程序崩溃。 因为变量number1被number2除,并且输出存储在结果变量中。 其中, number2的值为0 ,因此发生“除以零例外”

To handle such kind of exceptions, we use exception handling in C#.

为了处理这种异常,我们在C#中使用异常处理。

尝试抓住并最终阻止 (try catch and finally blocks)

Exception handling in C# can be handled using three blocks

C#中的异常处理可以使用三个块来处理

  1. try

    尝试

  2. catch

    抓住

  3. finally

    最后

Syntax of exception handling blocks,

异常处理块的语法,

    try
{
// code that can occur an exception
}
catch(Exception Type)
{
// code to handle the exception
// code to display the error message
}
finally
{
// code that should be executed
// whether exception is occurred or not
}

1) try block

1)尝试阻止

In this block, we write the code that can produce an exception or runtime error. For example, in the previous program, there was an exception (divide by zero).

在此块中,我们编写可能产生异常或运行时错误的代码。 例如,在上一个程序中,存在一个异常(除以零)。

2) catch block

2)挡块

This block is executed when the code throws an exception that is written in a try block, catch block catches the exception and we can write the code to handle that exception or any message to display the exception as per user preference.

当代码引发在try块中编写的异常,catch块捕获该异常,并且我们可以编写代码以处理该异常或根据用户喜好显示任何消息以显示该异常时,将执行此块。

Here, we used the exception classes, there are the following exception classes used in C# to catch the exceptions.

在这里,我们使用了异常类,C#中使用了以下异常类来捕获异常。

  1. Exception

    例外

  2. DivideByZeroException

    DivideByZeroException

  3. NullReferenceException

    NullReferenceException

  4. OutOfMemoryException

    OutOfMemoryException

  5. InvalidCastException

    InvalidCastException

  6. ArrayTypeMismatchException

    ArrayTypeMismatchException

  7. IndexOutOfRangeException

    IndexOutOfRangeException

  8. AirthmeticException

    AirthmeticException

  9. OverFlowExecption

    溢出执行

These classes are available in System namespace. In the above classes, the Exception class is a superclass and others are sub-classes, The Exception class can catch any kind of exception thrown by the try block.

这些类在System名称空间中可用。 在上面的类中, Exception类是超类,其他是子类, Exception类可以捕获try块引发的任何类型的异常。

3) finally block

3)最后封锁

finally block is executed in all cases i.e. whether the program is generating an exception or not, before leaving the program, compiler moves to the finally block. This block can be used to write the codes that are compulsory for the execution of program like the closing of the file, releasing the memory, etc.

在所有情况下都将执行finally块,即程序是否正在生成异常,在离开程序之前,编译器将移至finally块。 该块可用于编写执行程序所必需的代码,例如关闭文件,释放内存等。

Here is the code (with exception handling) to handle divide by zero exception.

这是处理零除异常的代码(带有异常处理)。

using System;
class Program
{static void Main()
{int number1 = 0;
int number2 = 0;
int result  = 0;
try
{Console.WriteLine("Enter Number : ");
number1 = int.Parse(Console.ReadLine());
result = number1 / number2;
Console.WriteLine("Result : " + result);
}
catch (DivideByZeroException e)
{Console.WriteLine(e.Message);
}
finally
{Console.WriteLine("Program exited normally");
}
}
}

Output

输出量

翻译自: https://www.includehelp.com/dot-net/exception-handling-in-csharp.aspx

c#异常处理

c#异常处理_C#中的异常处理相关推荐

  1. c ++异常处理_C ++中的异常处理

    c ++异常处理 In this article, we'll take a look at performing Exception Handling in C++. 在本文中,我们将介绍在C ++ ...

  2. Arm64中的异常处理

    闲话 最近优化环境中出现了多次不同种类的异常,其他文章中也有提及,为此专门去研究了一下Arm64的异常处理机制和代码,之前主要的开发和应用环境为X86,ARM接触很少,也没有机会去研究和学习,总以为不 ...

  3. kotlin中的异常处理_如何使用assertFailsWith在Kotlin中测试异常

    kotlin中的异常处理 by Daniel Newton 丹尼尔·牛顿 如何使用assertFailsWith在Kotlin中测试异常 (How to test exceptions in Kotl ...

  4. 编写高质量代码改善C#程序的157个建议——建议86:Parallel中的异常处理

    建议86:Parallel中的异常处理 建议85阐述了如何处理Task中的异常.由于Task的Start方法是异步启动的,所以我们需要额外的技术来完成异常处理.Parallel相对来说就要简单很多,因 ...

  5. SpringMVC 中的异常处理

    SpringMVC 中的异常处理 异常处理的思路 系统中异常包括两类:预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手段减 ...

  6. PHP如何进行错误与异常处理(PHP7中的异常处理和之前版本异常处理的区别)

    PHP如何进行错误与异常处理(PHP7中的异常处理和之前版本异常处理的区别) 一.总结 一句话总结: throwable接口+Error类 在PHP7更新中有一条:更多的Error变为可捕获的Exce ...

  7. 【转】Java中关于异常处理的十个最佳实践

    原文地址:http://www.searchsoa.com.cn/showcontent_71960.htm 导读:异常处理是书写强健Java应用的一个重要部分,Java许你创建新的异常,并通过使用 ...

  8. Swift41/90Days - 面向轨道编程 - Swift 中的异常处理

    问题 在开发过程中,异常处理算是比较常见的问题了. 举一个比较常见的例子:用户修改注册的邮箱,大概分为以下几个步骤: 接收到一个用户的请求:我要修改邮箱地址 验证一下请求是否合法,将请求进行格式转化 ...

  9. Laravel 中的异常处理

    Laravel 中的异常处理 参考文章: (1)Laravel 中的异常处理 (2)https://www.cnblogs.com/feiffy/p/10253842.html (3)https:// ...

最新文章

  1. 第二章 创建webGL设备和绘制缓冲区呈现 Context Creation and Drawing Buffer Presentation
  2. oracle密码不能重复用_重复码
  3. 操作系统文件分配策略_操作系统中的文件分配方法
  4. ASP.NET Core 基于SignalR实时通讯的前后端分离技术
  5. 【算法】剑指 Offer 63. 股票的最大利润
  6. java中实现多线程的两种基本方法
  7. 基于 GMDSS 的电子海图定位仿真研究
  8. msf win10漏洞_Kali对Windows2008/7的MS17010漏洞测试(MSF自带模块)
  9. 惠普打印机如何设置扫描到计算机,惠普打印机怎样扫描文件到电脑
  10. win10怎么快速锁定计算机,win10怎么快捷键锁定电脑_win10一键锁屏快捷键是什么-win7之家...
  11. 图片太普通,教你轻松制作画中画特效
  12. SDM、ESR、LBF、AAM
  13. 用python做名片管理器_Python简单的名片管理器
  14. LinuxProbe学习笔记(十一)
  15. 聚乙二醇表面修饰氧化锌量子点/FA-PEG-CdTe/CdS量子点荧光探针特异性标记Hep-2的制备
  16. 七大关键数据 移动安全迎来历史转折点
  17. 两大h264视频分析工具
  18. 微信小程序校园学生选课教学论坛信息管理系统SSM-JAVA【数据库设计、论文、源码、开题报告】
  19. QQ2011 Beta3优先体验(附官方体验地址及下载地址)
  20. Unity中鼠标的交互事件

热门文章

  1. 怎么玩转CSS内部样式表与外部样式表?
  2. 问题:三元向量的比较
  3. linux 函数 文件校验,Linux中的文件效验命令
  4. jar包是什么意思_面试难度五颗星:JVM有Full GC,为什么还会 OutOfMemoryError?
  5. FormatJS – 让你的 Web 应用程序国际化
  6. [译] SpaceAce 了解一下,一个新的前端状态管理库
  7. 如何存储和恢复 HTML5 Canvas 状态
  8. 我的GMAIL下蛋了,要的请留下姓,名和email!!
  9. Js引擎解析执行 阅读笔记
  10. SCREEN屏幕编程时候必须保证SCREN中词典的字段格式必须和数据表中字段的类型长度一致!...