Depends on what you're doing regarding exception handling...
If you want to pass your exceptions up to the higher level and handle the
errors there (generally an accepted rule of thumb of OOP), then make Add
void and not bool. If an error occurs, then the try/catch blocks in the
higher code will catch and deal with it.
You need to look at the code and decide what you want to happen should the
Add fail...
For example, if it makes no difference to what you're doing and it's not a
major problem, then log the problem as a warning (wrap the code as you have
done, but log it rather than rethrowing the error) and carry on.
If it is a major error and your application cannot proceed without it, then
you should catch the error higher up, log it if possible (whether to disk,
to database or message to the user), and shut the application down.
Another thing to consider which will play a part here is whether there is
anything that needs "shutting" down before leaving the function. I suspect
you'll be opening a database connection, which you'll want to close...
Do this like this inside your Add():
SqlConnection myConnection = new SqlConnection();
try
{
// open connection and do your stuff here
}
catch ( Exception ex )
{
throw ( ex );
}
finally
{
if ( myConnection.State == ConnectionState.Open )
{
myConnection.Close();
}
}
Finally, remember that you may want to catch certain kinds of exceptions...
For example, if the connection fails to be established (SqlException is
thrown), you could do something different in your exception handling than if
a null object was referenced...
"hplloyd" <hp*****@discussions.microsoft.com> wrote in message
news:49**********************************@microsof t.com...
Hi,
I have a function that adds data to a database and I want to return true
if
the database was updated and false if there was a problem, so I am using a
try... catch block...
My problem is that I can return true ok is the routine succeeds but where
do
I put the return false; statement id the process fails - I get a compile
error say unreachable code with whatever i try...
Code snippet:
public bool Add()
{
try
{
// Do stuff
return true;
}
catch (Exception ex)
{
throw new Exception ("Unable to update database " + ex.Message)
}
}
If i put return false before the throw then the throw is unreachable, if I
put it after then the return is unreachable.... what is the proper way to
do
this??
Thanks in advance