I'm not sure what that exception is meant to accomplish or why that was even attempted. If you're just looking to check if a value is less than 18, you can do that with a simple if
statement:
String s;
int i;
Scanner a = new Scanner(System.in);
System.out.println("Enter your Name: ");
s = a.nextLine();
System.out.println("Enter your Age: ");
i = a.nextInt();
if (i < 18) {
System.out.println("Sorry,you are not eligible");
// presumably exit the application here as well?
} else {
System.out.println("You are eligible for the deal!!!");
// presumably continue with other logic here as well?
}
As a general rule, never use exceptions for logic flow. Conditional constructs (if
statements, generally) exist for that purpose. An exception should be used to exit a method or operation in a faulted state so that the code consuming that method or operation can respond to that faulted state. Checking the age of the user isn't a faulted state, it's simply business logic.
As for why the code you have "doesn't work", there are a couple of issues...
This line will exit the code block immediately:
throw new AgeException();
This is because it, well, throws an exception. So nothing after that line will execute. The code will immediately go to the catch
block, so the behavior to expect here would be that the user is never prompted for input and always immediately told that they are eligible for the deal.
Additionally, there are three errors here:
if ((a.nextInt) > 18);
The first error is that there is no a
variable in that context. That variable is in the main
method. So it would need to be passed to that specifyException
method to use it.
The second error is that semi-colon. Unless the compiler complains about it syntactically (I'm not familiar enough with Java to know for certain) that will basically render the entire if
block moot because it represents an empty statement. So the whole block translates to "if the value is greater than 18, do nothing".
The third error is that you forgot the parentheses for nextInt()
.
Finally, even if you don't immediately throw the exception, nowhere do you call the specifyException
method. So that logic will never be invoked. If it seems unintuitive as to where or how you'd call that method, that's because it's on an exception and using exceptions for logic flow is inherently unintuitive and wrong :)