Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    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);
    		}
    		
    	}

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    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).


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •