如何在 C# 中捕获空引用异常?
它处理因引用空对象而生成的错误。当您试图访问指向空值的成员字段或函数类型时,将发生空引用异常。
假设我们有一个这样的空字符串 -
string str = null;
现在,您尝试获取空字符串的长度,然后它将导致异常 -
If(str.Length == null) {}上述异常将被抛出。现在,让我们看看如何防止抛出空指针异常 -
示例
using System;
class Program {
static void Main() {
int[] arr = new int[5] {1,2,3,4,5};
display(arr);
arr = null;
display(arr);
}
static void display(int[] arr) {
if (arr == null) {
return;
}
Console.WriteLine(arr.Rank);
}
}输出
1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP