多次抛出异常
Throwing exceptions multiple times
我有以下代码:
static int GetLastAddedIDHelper(OleDbConnection connection)
{
try
{
// Init variables.
OleDbCommand command = null;
string cmdText = "SELECT @@IDENTITY";
if (connection != null)
command = new OleDbCommand(cmdText, connection);
else
throw new ArgumentNullException("connection", "The connection was passed as null. Therefore the globally used connection is used but was never set.");
return (int)command.ExecuteScalar();
}
catch (Exception ex) { throw ex; }
}
public static int GetLastAddedID()
{
try
{
return GetLastAddedIDHelper(_Connection);
}
catch (Exception ex) { throw ex; }
}
private void Button_Click_Action()
{
try
{
int i = AccessDbServiceBase.GetLastAddedID();
}
catch (Exception ex)
{
MessageBox.Show(ExceptionHandler.GetExceptionMessage(ex));
}
}
以上代码将为我从 Access 数据库中获取最后插入的 ID。现在,要做到这一点,Button_Click_Action
将调用 GetLastAddedID
,然后将调用 GetLastAddedIDHelper
。当 exception
出现在 GetLastAddedIDHelper
时,我将异常抛至主方法 Button_Click_Action
。
我想知道我这样做的方式是否正确,比如 GetLastAddedID
中是否有必要,我是否应该使用 throw
而不是 throw ex
,... ?
您可能想要执行 throw;
因为 throw ex;
将重置堆栈跟踪。
GetLastAddedIDHelper
和 GetLastAddedID
中的异常处理在这种情况下没有任何用处。看起来,您的意图似乎是简单地捕获异常,然后除了重新抛出它之外什么都不做。如果是这样,那为什么还要费心去抓住它呢?只需让异常向上传播堆栈,直到可以处理它的异常处理程序获取它,在本例中的 Button_Click_Action
方法中。
在此示例中,您的异常处理实际上是有害的,因为 throw ex
会弄乱您的堆栈跟踪。您想改用 throw
。
我有以下代码:
static int GetLastAddedIDHelper(OleDbConnection connection)
{
try
{
// Init variables.
OleDbCommand command = null;
string cmdText = "SELECT @@IDENTITY";
if (connection != null)
command = new OleDbCommand(cmdText, connection);
else
throw new ArgumentNullException("connection", "The connection was passed as null. Therefore the globally used connection is used but was never set.");
return (int)command.ExecuteScalar();
}
catch (Exception ex) { throw ex; }
}
public static int GetLastAddedID()
{
try
{
return GetLastAddedIDHelper(_Connection);
}
catch (Exception ex) { throw ex; }
}
private void Button_Click_Action()
{
try
{
int i = AccessDbServiceBase.GetLastAddedID();
}
catch (Exception ex)
{
MessageBox.Show(ExceptionHandler.GetExceptionMessage(ex));
}
}
以上代码将为我从 Access 数据库中获取最后插入的 ID。现在,要做到这一点,Button_Click_Action
将调用 GetLastAddedID
,然后将调用 GetLastAddedIDHelper
。当 exception
出现在 GetLastAddedIDHelper
时,我将异常抛至主方法 Button_Click_Action
。
我想知道我这样做的方式是否正确,比如 GetLastAddedID
中是否有必要,我是否应该使用 throw
而不是 throw ex
,... ?
您可能想要执行 throw;
因为 throw ex;
将重置堆栈跟踪。
GetLastAddedIDHelper
和 GetLastAddedID
中的异常处理在这种情况下没有任何用处。看起来,您的意图似乎是简单地捕获异常,然后除了重新抛出它之外什么都不做。如果是这样,那为什么还要费心去抓住它呢?只需让异常向上传播堆栈,直到可以处理它的异常处理程序获取它,在本例中的 Button_Click_Action
方法中。
在此示例中,您的异常处理实际上是有害的,因为 throw ex
会弄乱您的堆栈跟踪。您想改用 throw
。