c#異常處理_C#中的異常處理

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#

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

輸出量

output in C#

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

c#異常處理

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377470.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377470.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377470.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

(轉)走進AngularJs(六) 服務

原文地址:http://www.cnblogs.com/lvdabao/p/3464015.html 今天學習了一下ng的service機制,作為ng的基本知識之一,有必要做一個了解,在此做個筆記記錄一下。 一、認識服務(service) 服務這個概念其實并不陌…

Linux驅動程序框架以及概述

目錄驅動程序三種基本類型(組成)設備驅動程序功能驅動程序的內核模塊機制(開發模式)驅動程序框架三個主要部分1、字符設備驅動程序框架2、塊設備驅動程序框架2、網絡設備驅動程序框架驅動程序三種基本類型(組成&#x…

curl 使用整理(轉載)

我一向以為,curl只是一個編程用的函數庫。 最近才發現,這個命令本身,就是一個無比有用的網站開發工具,請看我整理的它的用法。 curl網站開發指南 阮一峰 整理 curl是一種命令行工具,作用是發出網絡請求,然…

Linux內核邏輯結構

linux內核從邏輯上可以分為5個部分: 1、進程調度 進程調度控制進程對CPU的訪問。當需要選擇下一個進程運行時,由調度程序選擇最值得運行的程序。可運行進程實際上是僅等待CPU資源的進程,如果某個進程在等待其他資源,則該進程是不可…

對批量文件重命名

一、 文件夾下存放各種不同名稱的同類型文件 F:\test 二、重命名格式從a0開始,數字依次遞增,a0,a1,a2,a3… import ospathr"F:\test"#要修改文件的路徑 namer"a"#命名從什么開始 num0#默認從0開始,即a0,a1,a2...... …

替換Quartus 自帶編輯器 (轉COM張)

正文 此處以Quartus II 11.1和Notepad v5.9.6.2為例。 1. 使用QII自動調用Notepad來打開HDL、sdc、txt等文件;并且可以在報錯的時候,Notepad可以直接高亮所報錯的行(此模式下,Notepad最大化后效果最佳)。 方法&#xf…

scala 方法重載_Scala中的方法重載

scala 方法重載Scala方法重載 (Scala method overloading) Method overloading is a method that is redefined in different ways under the same name. Method overloading is one of the methods used to implement polymorphism in Scala. 方法重載是一種使用相同名稱以不…

C#網頁自動登錄和提交POST信息的多種方法 新人學習中

網頁自動登錄和提交POST信息的核心就是分析網頁的源代碼(HTML),在C#中,可以用來提取網頁HTML的組件比較多,常用的用WebBrowser、WebClient、HttpWebRequest這三個。 以下就分別用這三種方法來實現:1、WebBr…

四、采集和制作數據集

一、采集數據 安裝labelme:pip install labelme 打開labelme:labelme 將收集好的照片(320320,png格式)存放到一個文件夾中,例如我的是F:\test,再此文件夾下再創建個文件夾label用于存放標簽文件 使用labelme打開數據…

MTFBWU的完整形式是什么?

MTFBWU:愿力量與您同在 (MTFBWU: May The Force Be With You) MTFBWU is an abbreviation of “May The Force Be With You". MTFBWU是“愿力量與你同在”的縮寫 。 It is an expression, which is commonly used in messaging or chatting on social media n…

VMware14.0 安裝 CentOS7.2

大致流程 對于VMware14.0安裝包用百度網盤下載即可。 鏈接:https://pan.baidu.com/s/1DEGa47EbI1Fup_MTXhv0xg 提取碼:izo6 華為云CentOS7 下載劃線的。其他步驟與大致流程里一樣。 最后輸入root 以及配置的密碼即可:密碼輸入時是沒有任何顯…

基于visual Studio2013解決C語言競賽題之1049抓牌排序

題目解決代碼及點評/* 功能:插入排序。許多玩牌的人是以這樣的方式來對他們手中的牌進行排序的:設手中原有3張牌已排好序,抓1張新牌,若這張新牌的次序在…

學習Lucene筆記一:創建索引

public class HelloLucene {/*** 建立索引* param args*/public void index(){IndexWriter writer null; try {//1.創建Directory,// Directory directory new RAMDirectory();//索引是建立在內存中的Directory directory FSDirectory.open(new File("D:/Lucene/ind…

【C++進階】C++創建文件/屏幕輸出流類(將信息同時輸出到文件和屏幕)

在軟件的調試技術中,很重要的一個技術是將軟件運行過程中的一些信息寫入到“日志文件”中。但是同時還要將信息顯示到屏幕上,以方便程序員實時查看這些信息。 最簡單的一種辦法是這樣的: std::ofstream output("debug.log", ios::…

五、加載數據集

之前寫過加載數據集的一些小筆記,這里詳細內容就不再敘述了 詳細學習可以參考該博文二、PyTorch加載數據 一、分析 因為U-net網絡架構是輸入1通道,大小為(572,572)的灰度圖,圖片大小無所謂,我的思路是將三通道的圖像使用OpenCV進…

CDMA的完整形式是什么?

CDMA:碼分多址 (CDMA: Code Division Multiple Access) CDMA is an abbreviation of Code Division Multiple Access. Code Division Multiple Access is a digital cellular technology and displays a network of multiple accesses. The various radio communica…

BCD碼與十進制的相互轉換

BCD碼是用每四位代替一位十進制數(0 到 9 的某一位數) 例如:0x25 就代表25 十六進制的每位轉換成二進制代表四個位。 下面是bcd轉char short int long c語言程序 //************************************************************…

DSP關于存儲器讀寫、IO讀寫時序圖的注意點

這里的存儲器圖不涉及插入等待周期。 IO設備的圖可以自行減去插入等待周期,然后觀察。 存儲器讀讀寫 存儲器寫寫讀 I/O設備讀寫操作

折騰430 launchpad

launchpad到手也已經很長時間了,團購了一個g2的,一個鐵電的,現在馬上又要來一個g2的,感覺手上的東西太多了,急需消化一下,首先呢還是先把430搞定吧。 ---------------------------------------------------…

oem模式是什么_OEM的完整形式是什么?

oem模式是什么OEM:原始設備制造商 (OEM: Original Equipment Manufacturer) OEM is an abbreviation of "Original Equipment Manufacturer". Its meaning has changed over time. In former times, it alluded to a corporation that manufactures produ…