提问人: 提问时间:11/22/2022 更新时间:11/22/2022 访问量:55
C#,未捕获 NullReferenceException
C#, NullReferenceException is not catched
问:
下午好。我不明白,为什么没有调用块“catch”,而是程序停止使用 NullReferenceException。
string? nullable_string_1 = null;
try
{
string non_nullable_string_1 = (string)nullable_string_1;
System.Console.WriteLine(non_nullable_string_1.Length);
}
catch (System.NullReferenceException nullReferenceException)
{
System.Console.WriteLine($"There is an invalid operation exception with message: \"{nullReferenceException.Message}\"");
}
答:
1赞
Rajdeep Das
11/22/2022
#1
using System;
public class Program
{
public static void Main()
{
string? nullableString = null;
try
{
string nonNullableString = (string)nullableString;
Console.WriteLine(nonNullableString.Length);
}
catch (NullReferenceException nullReferenceException)
{
Console.WriteLine($"There is an invalid operation exception with message: \"{nullReferenceException.Message}\"");
}
Console.WriteLine("After Exception Code Run");
}
}
输出 - 它正在工作 [1]:https://i.stack.imgur.com/66Qum.png
评论
non_nullable_string_1.Length