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 3 of 3
  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,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 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).

  • #3
    New Coder
    Join Date
    Aug 2014
    Posts
    22
    Thanks
    0
    Thanked 0 Times in 0 Posts
    An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

    A user has entered invalid data.
    A file that needs to be opened cannot be found.
    A network connection has been lost in the middle of communications or the JVM has run out of memory.
    Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.


  •  

    Posting Permissions

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