Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0 DLL NET
Which way is the best way for handling exceptions in C# class library ?
In my dll I have something like this :
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 :
 
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 14-Feb-12 3:50am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Comments
cCoderNN at 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 at 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 at 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 at 14-Feb-12 9:37am
   
Well, maybe I should rename it.
Thank you :)
cCoderNN at 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;
}
SteveAdey at 14-Feb-12 10:20am
   
Yes, that looks good.
SAKryukov at 14-Feb-12 12:35pm
   
What's good about it? This is totally wrong. Logically, this is strictly equivalent to not catching exception! Obvious, after you think a bit about it, right? Only a waste of resources. In this code, you should do nothing about exception.
 
Please see my answer.
--SA
SAKryukov at 14-Feb-12 12:38pm
   
Please see my comment above -- this is wrong.
However, I must appreciate your code sample in the question -- it can make full sense. I explain it in more general case when I write about exclusions from the rule of thumb I mentioned in my answer -- please see.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  
Comments
SAKryukov at 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 at 15-Feb-12 3:10am
   
Agreed!

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 424
1 OriginalGriff 375
2 CHill60 230
3 CPallini 220
4 Maciej Los 210
0 Sascha Lefévre 75
1 OriginalGriff 70
2 F-ES Sitecore 55
3 Peter Leow 50
4 Dave Kreskowiak 40


Advertise | Privacy | Mobile
Web02 | 2.8.150327.1 | Last Updated 14 Feb 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100