You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# .NET嵌套try-catch块无法正确处理异常问题咨询

异常处理问题说明

我在演示异常处理时,故意使用了错误的表名,并将SqlDataReader dr设为null实例。内部try块可以捕获错误表引用引发的SqlClient.SqlException,但外部try块却无法捕获dr.HasRows处的NullReferenceException。

示例代码

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();
            }
        }
    }

内容的提问来源于stack exchange,提问作者Cshitiz Dhingra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:01:06