Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Which way is the best way for handling exceptions in C# class library ?
In my dll I have something like this :
C#
public bool Rename(string newName)
        {
            if (!this._parameters.Database.Equals(this.Database.Name))
                this._parameters.SelectDatabase(this.Database.Name);
            try
            {
                if (string.IsNullOrEmpty(newName))
                    throw new ArgumentException("Invalid new table name (NULL or empty).");

                using (MySqlConnection connection = new MySqlConnection(this._parameters.ConnectionString))
                {
                    connection.Open();
                    using (MySqlCommand command = new MySqlCommand(Queries.Rename(this.Name, newName), connection))
                    {
                        command.ExecuteNonQuery();
                    }
                    connection.Close();
                }
                this.Name = newName;
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


In my application, I check return value of method.
If it is true than it just continue with execution, otherwise it displays simple MessageBox with general error message.

Now I want to show more precise error to user, based on exception type and message.

May I do it like this :

C#
public bool Rename(string newName,out Exception exception)
        {
            if (!this._parameters.Database.Equals(this.Database.Name))
                this._parameters.SelectDatabase(this.Database.Name);
            try
            {
                if (string.IsNullOrEmpty(newName))
                    throw new ArgumentException("Invalid new table name (NULL or empty).");

                using (MySqlConnection connection = new MySqlConnection(this._parameters.ConnectionString))
                {
                    connection.Open();
                    using (MySqlCommand command = new MySqlCommand(Queries.Rename(this.Name, newName), connection))
                    {
                        command.ExecuteNonQuery();
                    }
                    connection.Close();
                }
                this.Name = newName;
                return true;
            }
            catch (Exception exc)
            {
                exception = exc;
                return false;
            }
        }

and then if method returns false I show a proper message and hint to the user.

Any better and faster way ?

Thanks in advance


Nikola
Posted

I personally like to handle exceptions as late as possible. For example if I were you, I will handle the exception at exact point where I want to show the message to user.

But the problem is, you can't throw up all the exception from core classes to the GUI level. You will have to write a million catch blocks. It is basically ugly. What you can do is soften up the exception by wrapping them in your own exceptions. This way, exception is re-thrown back as farther as possible, but in a manageable way.

Actually this is a design thing as well as a programming technique.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 14-Feb-12 11:36am    
You are basically right, but there are 1) exclusions, 2) technique of working with exceptions specific to UI. Also, you should have mentioned separate exception handling per thread.

I try to explain it all in my answer, please see.
--SA
krumia 15-Feb-12 3:10am    
Agreed!
For exceptions, there are no boundaries between assemblies. An exception operated on a stack, and each stack belongs to a thread.

Please see other answers.

Here is a rule of thumb: in most cases, don't catch exceptions in libraries. You need to catch exceptions on a very top stack frame of each thread.

There are exclusions: sometime you need to catch a raw exception, create a more semantic exception and re-throw it. In rare cases you can block exception propagation completely, as you can fully "fix" the problem during run-time. One such case is wrong user input, and the "fix" would be prompting the user again until the problem is resolved. However, this is not the usual and not the most recommended way. Another case of total blocking of the exception is working with some defected code which is not available in its source form for a patch.

UI has it's own exception handling strategy: catching all exception in the main event-oriented loop. I explain it in one of my past answers. Please see:

How do i make a loop that will stop when a scrollbar reaches the bottom[^],
When i run an application an exception is caught how to handle this?[^],
throw . .then ... rethrowing[^].

—SA
 
Share this answer
 
v2
If you want the exception in the calling code, you should really just throw the exception. i.e. take the try catch out of the method.

If you just want an error message, then you're probably better doing 'out string errorMessage' instead of the exception.
 
Share this answer
 
Comments
cCoderNN 14-Feb-12 9:02am    
I really don't want to have dll related error handling in application.
Also, beside exception message, I want exception type and some other properties.
SteveAdey 14-Feb-12 9:10am    
You will probably need exception handling in your application, otherwise you're just relying on the fact that you dlls are behaving nicely (not recommended). You asked for advice, this is mine :-)

You can add other properties to a specialised Exception that you create and then use the inner exception to house the one caught.
SteveAdey 14-Feb-12 9:21am    
BTW, if you're going to proceed with your current method (which I'm not saying you shouldn't), you should really rename it TryRename, that's the standard way of naming something like this.
cCoderNN 14-Feb-12 9:37am    
Well, maybe I should rename it.
Thank you :)
cCoderNN 14-Feb-12 10:10am    
What do you think about this
try
{
// Code
// Something goes wrong, throw exception
}
catch(Exception e)
{
// Write to log
throw;
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900