Results 1 to 4 of 4
  1. #1
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    CA, USA
    Posts
    264
    Rep Power
    6

    Default [SOLVED] multiple try catch

    Is there any difference between these two code fragments?

    Do I need a try statement for each exception?
    Java Code:
    try
    {
    	try
    	{
    		//Code to be executed
    	}
    	catch (NumberFormatException e) 
    	{
    		System.out.println("Error: Invalid parameters."); 
    		System.out.println(e);
    	}
    }
    catch (ArrayIndexOutOfBoundsException e)
    {
    	System.out.println("Error: Invalid parameters."); 
    	System.out.println(e);
    }
    Or does a single try statement handle both?
    Java Code:
    try
    {
    	//Code to be executed
    }
    catch (Exception e) 
    {
    	System.out.println("Error: Invalid parameters."); 
    	System.out.println(e);
    }

  2. #2
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    You can have multiple catch for each try block.
    Java Code:
    try {
        //Code to be executed
    }
    catch (NumberFormatException e) {
        //Handle error
    }
    catch (ArrayIndexOutOfBoundsException e) {
        //Handle error
    }
    That way you won't catch exceptions that you don't want to - better for debugging

  3. #3
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    CA, USA
    Posts
    264
    Rep Power
    6

    Default

    Ooooh... Thanks! : )

  4. #4
    Join Date
    Apr 2009
    Posts
    5
    Rep Power
    0

    Default

    in some way both work fine but the 1st one is more specific exception that u want to caught. the second one where u use exception which is a supper class of all exception can catch all. so can be a problem in debugging . but in the first example one need to make sure that all the code are reachable by compiler.

Similar Threads

  1. how to catch two exceptions in one catch()?
    By arnab321 in forum New To Java
    Replies: 1
    Last Post: 11-06-2008, 11:54 AM
  2. try catch...
    By MarkWilson in forum New To Java
    Replies: 8
    Last Post: 06-27-2008, 06:39 PM
  3. Try Catch
    By Renegade85 in forum New To Java
    Replies: 4
    Last Post: 12-03-2007, 05:10 PM
  4. when to use try...catch
    By javaplus in forum New To Java
    Replies: 2
    Last Post: 11-18-2007, 09:52 PM
  5. Use try and catch
    By zoe in forum New To Java
    Replies: 2
    Last Post: 07-25-2007, 08:50 PM

Posting Permissions

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