Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Exception handling

  1. #1
    Junior Member
    Join Date
    Nov 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Exception handling

    EDIT: I'm pretty sure I just figured this out but I still have so many questions!!

    I have 3 classes, the input reader class code was given to me, so I don't think I'm suppose to change that.
    This is what my lab says to

    InvalidInputException is a custom checked exception that you will write.

    NumberReader has a single field, of type InputReader. It has a method that repeatedly prompts the user to type a non-zero whole number. The user will type a zero to stop the loop. After the loop has finished, the sum of the input numbers will be displayed on the screen. This method must have a try catch block to catch a thrown InvalidInputException and display an error message if the user types something that is not an integer.


    I'm not asking you to do my homework, I want to know what you are doing and why.
    I have a lot of questions about this too (these aren't textbook questions, they are MY questions):

    1) Like why is the throw statement in the catch block? Shouldn't it be in the try block so when the program fails it catches itself and fixes the issue?
    2) When you throw InvalidInputException how does it know what you typed in? There isn't a line that is sending 'number' to that Class.
    3) Same with InputMismatchException, how does that know what you typed?
    4) my lab says 'this method must have a try catch block', does that mean I need a try catch in NumberReader????
    5) Arrgh!


    /**
     * This class reads the number you have inputted
     * 
     * @author (Lindsay LaPlante) 
     * @version (Nov 24th / 2011)
     */
    public class NumberReader
    {
        // instance variables - replace the example below with your own
        InputReader inputReader;
     
        /**
         * Constructor for objects of class NumberReader
         */
        public NumberReader()
        {
            // initialise instance variables
            inputReader = new InputReader();
        }
     
        /**
         * prompts user to type a non zero whole number
         */
        public void promptUser() throws InvalidInputException
        {
            int sumOfAllNumbersTyped = 0;
            int numberTyped;
     
            do{
                System.out.println("Input a non zero whole number: ");
                numberTyped = inputReader.getNumber();
                sumOfAllNumbersTyped += numberTyped;
            }while(numberTyped != 0);
     
            System.out.println("The sum of all numbers typed: " + sumOfAllNumbersTyped);
        }
    }


    import java.util.Scanner;
     
    /**
     * This class gets the number you have inputted
     * 
     * @author (Lindsay LaPlante) 
     * @version (Nov 24th / 2011)
     */
    public class InputReader
    {
        private Scanner scanner;
     
        public InputReader()
        {
            scanner = new Scanner(System.in);
        }
        /**
        This method returns the number typed by the user. If the number is
        not an integer it throws a custom checked exception that will be
        caught by the calling method.
        @throws InputMismatchException, InvalidInputException
        */
        public int getNumber() throws InvalidInputException
        {
            int number = 0;
            try {
                number = scanner.nextInt();
            }
            // catch any non-integer input
            catch(java.util.InputMismatchException exc) {
                scanner.nextLine(); // clear the buffer
                throw new InvalidInputException("not a valid number!");
            }
            return number;
        }
    }



    /**
     * This class says what is a valid number and what isn't.
     * 
     * @author (Lindsay LaPlante) 
     * @version (Nov 24th / 2011)
     */
    public class InvalidInputException extends Exception
    {
        // instance variables - replace the example below with your own
        private String message;
     
        /**
         * Constructor for objects of class InvalidInputException
         */
        public InvalidInputException(String message)
        {
            // initialise instance variables
            this.message = message;
        }
     
        /**
         * Getter method for message
         * @return message
         */
        public String getMessage()
        {
            return message;
        }
     
        /**
         * Overridden toString method
         * @return getMessage()
         */
        public String toString()
        {
            return getMessage();
        }
    }
    Last edited by JavaGirl9001; November 26th, 2011 at 04:49 AM.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Exception handling

    1. Examine what the code is doing. You don't want your getNumber() method to handle this exception, it's job is to try and read a number, and if it can't, raise an exception. If it's catching the InvalidInputException no exception gets thrown to the caller.

    2 & 3. You're right, it doesn't know anything by itself (well, that's not entirely true, just mostly true). In the case of the InputMismatchException, the Scanner object is reading in the data and trying to parse it as an integer. If it can't, it packages the necessary information it has into an InputMismatchException and throws it. Your InvalidInputException does basically the same thing (your getNumber() method is packaging a message into the InvalidInputException before throwing it).

    4. Yes, you do. The promptUser() method shouldn't throw any exceptions (you have it declared that it throws InvalidInputExceptions). Consider what you want to happen:

    while the user hasn't input a zero, keep asking the user to input numbers. If the input was a number, no exception gets thrown and everything should be executed normally. However, if there is an exception thrown you need to catch it and print out a message. The program should then repeat the query to input a number or zero to quit.

    Where would you place your try/catch block to accomplish this? What code should go inside the try block, and what code should go inside the catch block?

Similar Threads

  1. Exception Handling
    By hello_world in forum What's Wrong With My Code?
    Replies: 5
    Last Post: August 5th, 2011, 05:47 PM
  2. Need help with exception handling for a string
    By toppcon in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 6th, 2011, 06:59 AM
  3. [SOLVED] Embed a Jar into a website/Exception handling
    By Hallowed in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 31st, 2011, 07:34 AM
  4. Exception handling for TextFields
    By FretDancer69 in forum AWT / Java Swing
    Replies: 1
    Last Post: June 16th, 2009, 07:48 AM
  5. Exception handling
    By AnithaBabu1 in forum Exceptions
    Replies: 6
    Last Post: August 27th, 2008, 09:37 AM