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)。
![output in C#](https://i-blog.csdnimg.cn/blog_migrate/513bdc9598d2694937a71a0f29908336.png)
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#中的异常处理可以使用三个块来处理
try
尝试
catch
抓住
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#中使用了以下异常类来捕获异常。
Exception
例外
DivideByZeroException
DivideByZeroException
NullReferenceException
NullReferenceException
OutOfMemoryException
OutOfMemoryException
InvalidCastException
InvalidCastException
ArrayTypeMismatchException
ArrayTypeMismatchException
IndexOutOfRangeException
IndexOutOfRangeException
AirthmeticException
AirthmeticException
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
输出量
![output in C#](https://i-blog.csdnimg.cn/blog_migrate/edd5c73394e3dc8d7f36c38d85bccf9e.png)
翻译自: https://www.includehelp.com/dot-net/exception-handling-in-csharp.aspx
c#异常处理