CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   Exception Handling (http://www.codingforums.com/showthread.php?t=281566)

godz1990 11-08-2012 03:52 PM

Exception Handling
 
I'm trying to create a function to add an item to a list. How do I correctly implement exception handling, I don't think mine works.

Code:

        public void addItem(T item)
        {
                try
                {
                // check if correct type
                if (item instanceof GenericFood)
                        super.addItem(item);
                else if (item instanceof GenericElectronics)
                        super.addItem(item);
                else
                        throw new Exception("Error, not a generic item."); 
                }
                catch (Exception e)
                {
                        String msg = e.getMessage();
                        System.out.println(msg);
                        System.exit(0);
                }
               
        }


Fou-Lu 11-08-2012 04:22 PM

Looks like it'll work fine to me.
You don't need to do it at all though. Since you are throwing explicitly in the same block as the try, to me you may as well just use the condition to print the message and exit instead of throwing at all. Ideally, you would throw without a try/catch at all and let the caller decide what to do (if its a cli application it'll issue the print messages, if its a gui it will present the error). The collection shouldn't be responsible for this output at all.
You can also get around that completely if GenericFood and GenericElectronics is given a common super interface. Given that they are both allowed in the list anyway, this indicates that the T generic already matches a commonality between the two, so its questionable if it necessary for any checks in the addItem (and hence no override necessary).


All times are GMT +1. The time now is 01:32 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.