Results 1 to 7 of 7
  1. #1
    DerekRaimann is offline Member
    Join Date
    Dec 2010
    Posts
    45
    Rep Power
    0

    Default Custom exception exits program, while NumberFormatException only shows error

    I created an exception called NegativeNumberException as a test from a book I am reading. The code is as follows:

    class NegativeNumberException extends Exception {
    public NegativeNumberException() {
    super();
    }

    public NegativeNumberException(String msg) {
    super(msg);
    }
    }

    My code "trys" a block of code and catches two possible exceptions:

    try {
    // code of program
    } catch (NumberFormatException nfe) {
    System.out.println("Error: " + nfe.getMessage());
    } catch (NegativeNumberException nne) {
    System.out.println("Error: " + nne.getMessage("Error:Arguments
    must all be positive values."));
    }

    I ran the program which takes multiple arguments which are meant to be positive values, and must be numeric. When it encounters an argument with a nonnumeric value, the NumberFormatException is caught and it displays the general error message and continues execution of the program. However, when it encounters my custom exception NegativeNumberException, it displays the error message and exits the program. Why does it exit the program when the NegativeNumberException is executed?

    I tried to do some research on my own by looking at the code for NumberFormatException and see if it did anything different, and it obviously traced back to being a subclass of Exception, just like NegativeNumberException. I don't understand why mine exits. If any more code is needed I can post it, but I didn't think it would be necessary considering all of the workings of this should be in the definition of the exception i created, at least i think.

    I appreciate any and all help given, thanks!

    -Derek Raimann

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default

    There's something you're not showing us here.

    If that is the flow of your program, then both exceptions will continue after the catch.
    If there is no more code after the catch then they will both exit.

    On catching exceptions it is generally a good idea to print the stack trace as well. In this case it might help you see where the exceptions are actually coming from.

  3. #3
    DerekRaimann is offline Member
    Join Date
    Dec 2010
    Posts
    45
    Rep Power
    0

    Default

    I printed the stack trace and it leads back to a few things: the line that the exception was thrown. Here is the output:

    C:\j21work>java PrimeThreads a 1 b -1 4
    Error: For input string: "a"
    Looking for prime 1
    Error: For input string: "b"
    NegativeNumberException: Negative number used: -1. All arguments must be positive numeric values.
    at PrimeFinder.<init>(PrimeFinder.java:11)
    at PrimeThreads.<init>(PrimeThreads.java:12)
    at PrimeThreads.main(PrimeThreads.java:3)

    Here is the code to the two files I am using(sorry it doesn't show proper spacing for the code, even though I used tabs the forum won't show them):

    Main file: PrimeThreads.java:
    Java Code:
            public class PrimeThreads {
    		public static void main(String[] arguments) {
    			PrimeThreads pt = new PrimeThreads(arguments);
    		}
    		
    		public PrimeThreads(String[] arguments) {
    			try {
    				PrimeFinder[] finder = new PrimeFinder[arguments.length];
    				for (int i = 0; i < arguments.length; i++) {
    					try {
    						long count = Long.parseLong(arguments[i]);
    						finder[i] = new PrimeFinder(count);
    						System.out.println("Looking for prime " + count);
    					} catch (NumberFormatException nfe) {
    						System.out.println("Error: " + nfe.getMessage());
    					}
    				}
    				boolean complete = false;
    				while (!complete) {
    					complete = true;
    					for (int j = 0; j < finder.length; j++) {
    						if (finder[j] == null) continue;
    						if (!finder[j].finished) {
    							complete = false;
    						} else {
    							displayResult(finder[j]);
    							finder[j] = null;
    						}
    					}    
    					try {
    						Thread.sleep(1000);
    					} catch (InterruptedException ie) {
    						// do nothing
    					}
    				}
    			} catch (NumberFormatException nfe) {
    				//System.out.println("Error: " + nfe.getMessage());
    				nfe.printStackTrace();
    			} catch (NegativeNumberException nne) {
    				//System.out.println("Error: " + nne.getMessage());
    				nne.printStackTrace();
    			}
    		}
    
    		private void displayResult(PrimeFinder finder) {
    			System.out.println("Prime " + finder.target
    				+ " is " + finder.prime);
    		}		
    	}
    And the other class file used: PrimeFinder.java:
    Java Code:
    	public class PrimeFinder implements Runnable {
    		public long target;
    		public long prime;
    		public boolean finished = false;
    		private Thread runner;
    				
    		PrimeFinder(long inTarget) throws NegativeNumberException {
    			target = inTarget;
    			
    			if (target < 0) {
    				NegativeNumberException nne = new NegativeNumberException("Negative number used: " + target + ". All arguments must be positive numeric values.");
    				throw nne;
    			}
    			
    			if (runner == null) {
    				runner = new Thread(this);
    				runner.start();
    			}
    		}
    	
    		public void run() {
    			long numPrimes = 0;
    			long candidate = 2;
    			while (numPrimes < target) {
    				if (isPrime(candidate)) {
    					numPrimes++;
    					prime = candidate;
    				}
    				candidate++;
    			}
    			finished = true;
    		}
    
    		boolean isPrime(long checkNumber) {
    			double root = Math.sqrt(checkNumber);
    			for (int i = 2; i <= root; i++) {
    				if (checkNumber % i == 0)
    					return false;
    			}
    			return true;
    		}
    	}
    	
    	class NegativeNumberException extends Exception {
    		public NegativeNumberException() {
    			super();
    		}
    		
    		public NegativeNumberException(String msg) {
    			super(msg);
    		}
    	}
    There has to be something causing the program to exit, I just can't figure out why. Thanks again for helping with this!

    -Derek Raimann
    Last edited by DerekRaimann; 12-09-2010 at 07:14 AM.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default

    Can you use code tags please?
    Unformatted code is really difficult to follow the flow of.

    ETA: Also which is line 12 of PrimeThreads?
    Last edited by Tolls; 12-08-2010 at 11:19 AM.

  5. #5
    DerekRaimann is offline Member
    Join Date
    Dec 2010
    Posts
    45
    Rep Power
    0

    Default

    I fixed the code to use code tags from my preceding post in the forum, just look back to my last post and you will see the code.

    Line 12 of PrimeThreads.java is:

    finder[i] = new PrimeFinder(count);

    *** I believe I figured it out ***

    The problem I had trouble realizing was that there was a try clause in the beginning of the code that only caught NumberFormatException and returned execution to a for loop that was being tried from inside. The only catch statement that caught exceptions for NegativeNumberException was at the end of the main code block, with no for loop to return execution to,thereby exiting the application. Is there anything I left out or was too vague about, or should I mark this as solved?

    Thank you again for your time and patience!

    -Derek Raimann
    Last edited by DerekRaimann; 12-09-2010 at 07:58 AM.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default

    I suspected that was it, but couldn't follow the flow without the code tags.
    Good job on finding it yourself.
    :)

  7. #7
    DerekRaimann is offline Member
    Join Date
    Dec 2010
    Posts
    45
    Rep Power
    0

    Default

    Thanks go to you Tolls :) As a perk of this discussion I got to learn about printStackTrace() from you as well and how to format using code tags.I learn something new everyday! Take care!

    -Derek Raimann

Similar Threads

  1. NumberFormatException error
    By saran87 in forum New To Java
    Replies: 3
    Last Post: 08-24-2009, 04:51 PM
  2. Exception java.lang.NumberFormatException
    By vasavi.singh in forum New To Java
    Replies: 3
    Last Post: 02-24-2009, 06:27 AM
  3. Replies: 7
    Last Post: 01-30-2009, 06:40 AM
  4. Payroll Program exits at wrong time
    By jsand2 in forum Java Applets
    Replies: 13
    Last Post: 01-26-2009, 03:10 AM
  5. Error: NumberFormatException
    By coco in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 07:41 AM

Posting Permissions

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