-3

First of all, I would just like to say that I know this program could be completedly more easily by using an if-else configuration or a while loop, but I want to know how to do it using the exception class. (I'm guessing I need to use a custom made exception utilizing the try-catch block).


import java.util.Scanner;

class AgeChecker
{
    public static void main(String [] args)
    {
        Scanner inputdata = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = inputdata.nextLine();
        System.out.print(name+", enter your age: ");
        int age = inputdata.nextInt();
        try
        { // age entered must be between 0-125 (how to trigger exception in catch block?)
            System.out.println("You entered: "+age);
        }
        catch(Exception e)
        {
            System.out.println("Out of range error! (must be between ages 0 and 125)"+e);
        }
        finally
        {
            System.out.println("Age Checking Complete.");
        }
    }
}
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
wannabeprogrammer
  • 125
  • 1
  • 3
  • 9
  • [How to throw exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html). – Jeffrey Aug 03 '13 at 05:15
  • how can `System.out.println("You entered: "+age);` throw an `Exception` ? – jmj Aug 03 '13 at 05:15
  • 1
    @JigarJoshi He wants to throw an exception if the age is out of range. (Read the comment one line below `try`.) – Jeffrey Aug 03 '13 at 05:16
  • That is my problem; I'm not sure how to trigger the catch block. If I could somehow do that, my problem would already be resolved. – wannabeprogrammer Aug 03 '13 at 05:16
  • @thynoob Take a look at the tutorial I linked you to. And as you already observed, you should be using an `if-else` statement here instead of a `try-catch`. Throwing and catching exceptions is considerably more resource intensive than a simple `if-else`. – Jeffrey Aug 03 '13 at 05:18
  • Yes, I stated that I was aware of that in my title. Thank you for pointing that out again. :) My issue is that I just want to be able to implement the exception class. Am I on the right path? – wannabeprogrammer Aug 03 '13 at 05:19

4 Answers4

1

While I am not sure why you don't use an if-else instead of an exception, you can make custom Exceptions by subclassing existing exception classes. Generally you will subclass Exception for "declared" exceptions, and RuntimeException for exceptions that you don't want to have to catch. In your case you could just subclass Exception, like:

public MyException extends Exception
{
}

and then throw it if you find a range problem:

throw new MyException();

then catch it either by catching Exception, like you do or MyException:

catch(MyException exp) ...
sasbury
  • 301
  • 1
  • 4
1
package example.stackoverflow;

import java.util.Scanner;

public class AgeChecker
{
    public static final int MIN_AGE = 0;
    public static final int MAX_AGE = 125;

    static class InvalidAgeException extends Exception
    {
        private static final long serialVersionUID = 1340715735048104509L;

        public InvalidAgeException()
        { }

        public InvalidAgeException(String message)
        {
            super(message);
        }

        public InvalidAgeException(String message, Throwable cause)
        {
            super(message, cause);
        }
    }

    public static void main(String[] args)
    {
        Scanner inputdata = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = inputdata.nextLine();
        System.out.print(name+", enter your age: ");
        int age = inputdata.nextInt();
        try
        {
            System.out.println("You entered: "+age);
            // Assuming age limits are non-inclusive
            if( (age <= MIN_AGE) || (age >= MAX_AGE) )
            {
                throw new InvalidAgeException("Out of range error! (must be between ages 0 and 125)");
            }
        }
        catch(InvalidAgeException e)
        {
            e.printStackTrace();
        }
        finally
        {
            System.out.println("Age Checking Complete.");
            if(inputdata != null)
            {
                inputdata.close();
            }
        }
    }
}

Also note that you need to close() your Scanner whenever you're done with it. It is often useful to do such cleanup in a finally block, so that's where I've put it in this example.

Buzz Killington
  • 1,039
  • 9
  • 14
  • what is the purpose of the 'private static final long serialVersionUID = 1340715735048104509L'? – wannabeprogrammer Aug 03 '13 at 05:30
  • 1
    @thynoob: Throwable (which Exception extends) implements the Serializable interface - "it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization." (http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html) – Buzz Killington Aug 03 '13 at 05:35
  • so if I don't include that long, then there is a chance that the compiler may randomly throw an error even when there isn't one there? (essentially) – wannabeprogrammer Aug 03 '13 at 06:15
0

You are allowed to create your own instances of Exception. If you want to trigger a catch block, you need to throw the Exception from your try:

try {
    System.out.println("Enter your age: ");
    int age = scanner.nextInt();
    if(isInvalid(age)) {
        throw new Exception("Age is invalid!");
    }
} catch (Exception e) {
    // etc
}

You might also want to consider subclassing Exception to provide a little bit more information about what caused the problem.

Community
  • 1
  • 1
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • I just assumed that if you used (catch (Exception e)), then it would print out the error/exception detected in the try block by the catch block. – wannabeprogrammer Aug 03 '13 at 05:28
  • @thynoob Only if you call [`e.printStackTrace`](http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace()). – Jeffrey Aug 03 '13 at 05:30
  • so essentially, if you use the user-defined catch (Exception e) then you need to use e.printStackTrace? (I'm guessing this automatically detects the error for you) and like only if you do the system's tr-catch block then you can do the 'regular' approach where you do: try { // code } catch (Exception e) { System.out.println("You cannot do that."+e); } – wannabeprogrammer Aug 04 '13 at 02:10
  • 1
    @wannabeprogrammer Correct – Jeffrey Aug 04 '13 at 03:15
0
public class yourExcetionActivity extends Exception 
{
    public yourExcetionActivity() { }
    public yourExcetionActivity(String string) {
        super(string);
    }
}
DHN
  • 4,807
  • 3
  • 31
  • 45
Exceptional
  • 2,994
  • 1
  • 18
  • 25