NullReferenceException C#中的异常
什么是NullReferenceException? (What is NullReferenceException?)
NullReferenceException is an exception and it throws when the code is trying to access a reference that is not referencing to any object. If a reference variable/object is not referencing to any object, then it will be considered as null. And, when the code tries to access this variable/object, there will be an exception known as NullReferenceException.
NullReferenceException是一個異常,當代碼嘗試訪問未引用任何對象的引用時,將引發NullReferenceException 。 如果引用變量/對象未引用任何對象,則將其視為null 。 并且,當代碼嘗試訪問此變量/對象時,將存在一個稱為NullReferenceException的異常。
To handle NullReferenceException, we can write the code/message in catch block by using the NullReferenceException class.
為了處理NullReferenceException ,我們可以使用NullReferenceException類在catch塊中編寫代碼/消息。
C#中的NullReferenceException示例 (Example of NullReferenceException in C#)
using System;class Sample {public void SayHello(){Console.WriteLine("Hello World");} }class Program {static void Main(){Sample s = null;try{s.SayHello();}catch (NullReferenceException e){Console.WriteLine("EXCEPTION: "+e.Message);}} }Output
輸出量
EXCEPTION: Object reference not set to an instance of an objectIn the above program, we created a class "Sample" that contains a Method SayHello(), then we created another class that consumes class "Sample", then we create a reference of class "Sample" and assign null to reference s. We further called the method SayHello() using reference s, but it is not initialized properly. Thus, it generates NullReferenceException which is being caught in the catch block.
在上面的程序,我們創建了一個類“樣本”,它包含一個方法的SayHello(),然后我們創建另一個類,消耗類的“樣本”,然后我們創建一流的“樣本”,并指定空的參考秒的參考。 我們還使用引用s調用了方法SayHello() ,但未正確初始化。 因此,它將生成NullReferenceException ,該異常將被捕獲??在catch塊中。
Read more:
:
Exception handling in C#
C#中的異常處理
C# exception handling with multiple catch blocks
具有多個catch塊的C#異常處理
User Defined Exceptions in C#
C#中的用戶定義異常
翻譯自: https://www.includehelp.com/dot-net/NullReferenceException-exception-in-csharp.aspx
總結
以上是生活随笔為你收集整理的NullReferenceException C#中的异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 密码学电子书_密码学中的电子密码书(EC
- 下一篇: Java Short类hashCode(