C# NullReferenceException
Program.cs
string s = null;
Console.WriteLine(s.Length);
Output
kodingwindow@kw:~/csharp$ dotnet run
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
    at Program.<Main>$(String[] args) in /home/kodingwindow/csharp/Program.cs:line 2 
kodingwindow@kw:~/csharp$ 
C# program to demonstrate the use of try and catch blocks
Program.cs
try
{
    string s = null;
    Console.WriteLine(s.Length);
}
catch(NullReferenceException e)
{
    Console.WriteLine("String is null, hence, unable to find the length.");
}
Output
kodingwindow@kw:~/csharp$ dotnet run
String is null, hence, unable to find the length.
kodingwindow@kw:~/csharp$ 
C# program to demonstrate the use of try with multiple catch blocks
Program.cs
try
{
    string s = null;
    Console.WriteLine(s.Length);
}
catch(InvalidOperationException e)
{
    Console.WriteLine("Exception caught in the first catch block");
}
catch(NullReferenceException e)
{
    Console.WriteLine("Exception caught in the second catch block");
}
Output
kodingwindow@kw:~/csharp$ dotnet run
Exception caught in the second catch block
kodingwindow@kw:~/csharp$ 
Advertisement