Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-08-2012, 03:52 PM   PM User | #1
godz1990
New to the CF scene

 
Join Date: Oct 2012
Posts: 3
Thanks: 1
Thanked 0 Times in 0 Posts
godz1990 is an unknown quantity at this point
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);
		}
		
	}
godz1990 is offline   Reply With Quote
Old 11-08-2012, 04:22 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,650
Thanks: 4
Thanked 2,451 Times in 2,420 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
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).
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:40 PM.


Advertisement
Log in to turn off these ads.