赞
踩
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块中编写代码/消息。
- 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 object
In 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:
阅读更多:
翻译自: https://www.includehelp.com/dot-net/NullReferenceException-exception-in-csharp.aspx
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。