![](/img/trans.png)
[英]How to properly do Exception Handling with try and catch using C#
[英]C# .NET: nested try catch block not handling exception properly
为了演示异常处理,我故意将错误的表名和 null 实例放到SqlDataReader dr
中。 内部 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();
}
}
}
这段代码有很多问题,很难知道从哪里开始:
NullReference
是荒谬的:除非ExecuteReader
失败并且您捕获了SqlException
,否则您不会得到一个,在这种情况下,您应该将catch (SqlException
移到外部,然后您可以删除catch (NullReferenceException
。conn
cmd
和dr
需要using
.while (dr.HasRows)
没有意义,应该是while (dr.Read())
SELECT *
,仅使用 select 您需要的列。GetString(0)
,而是使用列名。static void Main(string[] args)
{
try
{
using (var conn = new SqlConnection(YourConnString))
using (var cmd = new SqlCommand("Select SomeColumn from Room_Entry1", conn))
{
conn.Open();
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
Console.WriteLine("DATA FOUND");
while (dr.HasRows)
{
Console.WriteLine(dr["SomeColumn"]);
}
}
}
}
}
catch (SqlException ex)
{
Console.WriteLine("****" + ex.Message);
}
catch (Exception out_Ex)
{
Console.WriteLine("##try2###" + out_Ex.Message);
}
Console.ReadKey();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.