Search code examples
c#exceptiontry-catchthrow

having issues using custom exceptions in C#


I have a form program I wrote in Visual Studio 2010. In the program I wrote new exceptions file called LibraryGeneralExceptions.cs

namespace Database
{
    public class LibraryGeneralExceptions : Exception
    {
        public LibraryGeneralExceptions()
        {
        }

        public void ItemInsertError()
        {
            MessageBox.Show("Item Insert Error", "Error");
        }

        ...
    }
}

under the same namespace I have

public void ItemInsert(string name,string creator,string publishing,string itemType,string genere, string year)
{
    ...
    if (errorMsg.Length != 0)
    {
       throw new ItemInsertError();
        MessageBox.Show(errorMsg, "error");
    }

under another namespace that uses Database and calls for functions from Database i'm trying to set up a try-catch to catch exceptions that database will make using LibraryGeneralExceptions, but I cannot seem to make it work for some reason.


Solution

  • lakovl it seems you may be misunderstanding how exceptions work in C#. One point of reference you may like to start reading is the MSDN article on exceptions and exception handling, please also review the child sections.

    When an exception is thrown it is a point at where a fault occurred, when caught it is being handled, and when re-thrown via a wrapped exception it is a reference that you tried to resolve a fault and couldn't or were simply catching to log.

    To be analogous imagine you have a chain of people, an ice-cream truck has arrived and one person asks someone to go and buy them an ice-cream, they run off to the truck only to find that the original person didn't give them enough money. The ice-cream vendor throws an exception InsufficientFundsException which is caught and re-thrown by the colleague. Now, if the collegue is generous enough they may wish to add finding for them, though if they also don't have funds they will re-throw the exception by wrapping it up. Finally they run back to the originator (this is called bubbling up) which they may then resolve or abandon.

    Now lets examine what you've done with your exception. What you've tried to do is create an exception type LibraryGeneralExceptions which is fine (except for the plural form, drop the s) though you have created a method ItemInsertError which in your code are treating it as if it is an exception of its own. So let's try fix your problem.

    Firstly it looks as though you intended to use LibraryGeneralExceptions as a sub-namespace and ItemInsertError is meant to be an exception, so here is a correct implementation:

    namespace Database {
        public class ItemInsertError : Exception {
            public ItemInsertError() : base() {}
            public void ItemInsertError(string message) : base(message) {}
        }
    }
    

    Now let's examine your insert method, the first thing wrong is you're handling the exception and alerting the user at the same time, instead, let's just handle the exception.

    public void ItemInsert(string name,
                           string creator,
                           string publishing,
                           string itemType,
                           string genre,
                           string year) {
        // ...
        if (errorMsg.Length != 0) {
           throw new ItemInsertError(errorMsg);
        }
    }
    

    So now when we invoke the ItemInsert method we will then handle exceptions in that piece of code.

    try {
        ItemInsert("name", "creator", "publishing", "itemType", "genre", 2012);
    } catch (ItemInsertError ex) {
        MessageBox.Show(
            ex.Message, "Error during insert",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    

    From this your user will now have feedback of what went wrong, your client code can now try to recover as in where my prior example decides if we can find more funds or not.