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#中的異常處理可以使用三個塊來處理
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
輸出量
翻譯自: https://www.includehelp.com/dot-net/exception-handling-in-csharp.aspx
c#異常處理