trycatch函数出现问题
本文关键字:问题 函数 trycatch | 更新日期: 2023-09-27 18:01:03
我有两个类。使用Generic Data Access类,我可以从存储过程GetDepartments中获取部门。我的问题是,在Catalog Access类中,尤其是在公共静态DataTable ExecuteSelectCommand(DbCommand命令((执行命令并将结果作为DataTable对象返回(中,我不知道必须在CATCH循环中写什么,也不知道如何将其留空。有人能帮我完成这部分吗?或者我怎么能在没有Try-catch的情况下改变它。
using System;
using System.Data;
using System.Data.Common;
using System.Configuration;
public static class GenericDataAccess
{
static GenericDataAccess()
{
}
public static DataTable ExecuteSelectCommand(DbCommand command)
{
DataTable table;
try
{
command.Connection.Open();
DbDataReader reader = command.ExecuteReader();
table = new DataTable();
table.Load(reader);
reader.Close();
}
catch (...)
{
......
}
finally
{
command.Connection.Close();
}
return table;
}
public static DbCommand CreateCommand()
{
string dataProviderName = BalloonShopConfiguration.DbProviderName;
string connectionString = BalloonShopConfiguration.DbConnectionString;
DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);
DbConnection conn = factory.CreateConnection();
conn.ConnectionString = connectionString;
DbCommand comm = conn.CreateCommand();
comm.CommandType = CommandType.StoredProcedure;
return comm;
}
}
**The Catalog Access class:**
using System;
using System.Data;
using System.Data.Common;
public static class CatalogAccess
{
static CatalogAccess()
{
}
public static DataTable GetDepartments()
{
DbCommand comm = GenericDataAccess.CreateCommand();
comm.CommandText = "GetDepartments";
return GenericDataAccess.ExecuteSelectCommand(comm);
}
}
如果您不知道该做什么或不想处理任何异常,请退出catch
。这是有效的:
try
{
// code here
}
finally
{
// cleanup here
}
这样,任何异常都将传递给调用您的方法的方法。如果try
块中存在问题(异常(,则该方法将退出,但不会在执行finally
中的任何代码之前退出。
在处理异常时,您有两种选择:您可以在抛出异常时立即处理它们,也可以让它们在代码中冒泡并稍后处理。哪个更好取决于你的程序到底做了什么。
如何处理它也取决于您的代码。是否要通知用户?是否重试连接?二者都什么都不做(坏!(?比方说,你只是想让用户知道发生了一些不好的事情。然后你可以做如下操作:
try{
// breakable stuff
}catch(Exception e){
System.Windows.Forms.MessageBox.Show("Something broke: " + e.Message);
}finally{
// clean up
}
如果您想进一步处理异常(也就是调用此异常的方法(,请执行以下操作:
try{
// breakable stuff
}catch{
throw;
}finally{
// clean up
}
我不知道该要求什么,但我怀疑您不想在函数中处理异常,而是让它在堆栈中按比例传播(即让调用方处理它(。
为了实现这一点,您可以将catch
-子句排除在代码之外。finally
以下的代码仍将被调用。如果您希望在函数中处理异常,但在返回之前重新抛出,请尝试:
catch (MyException e)
{
// Do stuff with e
throw;
}