To demonstrate Exception Handling, I have intentionally put the wrong table name and null instance to SqlDataReader dr. The Inner try block catches the wrong table reference exception SqlClient.SqlException but the outer try block fails to catch the NullReferenceException on dr.hasRows.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exp_Handling
{
internal class Program
{
static void Main(string[] args)
{
SqlConnection conn;
SqlCommand cmd;
//SqlDataReader dr;
try
{
conn = new SqlConnection(@"data source=ITEM-S132712\MSSQLSERVER2019;initial catalog=Hotel;integrated security=true");
cmd = new SqlCommand("Select * from Room_Entry1", conn);
conn.Open();
SqlDataReader dr = null;
try
{
dr = cmd.ExecuteReader();
}
catch (SqlException ex)
{
Console.WriteLine("****" + ex.Message);
}
if (dr.HasRows)
{
Console.WriteLine("DATA FOUND");
while (dr.HasRows)
{
Console.WriteLine(dr.GetString(0));
}
}
}
catch (System.NullReferenceException nullExp)
{
Console.WriteLine("##try1###" + nullExp.Message);
Console.WriteLine("Instance is Null for DataReader");
}
catch (Exception out_Ex)
{
Console.WriteLine("##try2###" + out_Ex.Message);
}
Console.ReadKey();
}
}
}
Demonstration from Reference https://www.mssqltips.com/sqlservertip/6055/net-exception-handling-for-database-calls-to-sql-server-with-try-catch-and-finally/