Java: Exception Handling not working - java

i have a program that I am trying to add exception handling to. The problem is, the exception that i wrote up still exits the program. Basically i offer the user to enter in any int, if they throw me a char, the exception says that they cant do that and lets them enter another int. But it isn't working giving me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at cit130_hw10_q3.Cit130_hw10_q3.main(Cit130_hw10_q3.java:29)
Java Result: 1
Here's some code. Thanks for any help you might offer.
Scanner input = new Scanner(System.in);
System.out.println("Enter a series of integers." +
"When finished enter 999");
int userInput = 0;
int inputCount = 0;
do{
try{
System.out.println("Enter an integer: ");
userInput = input.nextInt();
addToArray(userInput, inputCount);
}
catch(Exception e){
System.out.println("Only integer values are accepted. Please try again");
}
inputCount++;
}while (userInput != 999);
public static void addToArray(int nextInt , int inputCount){
integerArray[inputCount] = nextInt;
}

I suspect you forgot to recompile in-between or are running some other version of the code, maybe a different file than this. If you have java.lang.Exception catched like you show, this will ot happen.
Other option is that you have input.nextInt(); somewhere else, too, in a part that you did not paste here. Reconfirm line 29.

Excpetion class is the base class for all exceptions and if you are unsure of exception type you can catch it through java.lang.Excpetion and this works perfectly. In your case please put a break point in the try catch block and then confirm the point where exception is thrown. This will give an insight as why it is not getting catched at the place you mentioned

Related

How to properly use Exception method getMessage

I have the following java code:
System.out.print("\fPlease Enter an integer: ");
while(!validInt){
try{
number = kb.nextInt();
validInt = true;
}catch(InputMismatchException e){
System.out.print("Pretty please enter an int: ");
System.out.print(e.getMessage());
kb.nextLine();
continue;
)
kb.nextLine();
}
how can I set e.getMessage() so that System.out.println(e.getMessage()) will print "Pretty please enter an int: "
You only set the message when the exception is created, it's an argument to the constructor. In your case it would have been nice if the InputMismatchException was created like this:
tnrow new InputMismatchException("Pretty please enter an int: ")
Since you probably aren't creating the InputMismatchException, you can't set it's message, however inside a catch you can do something liket this:
catch(InputMismatchException ime){
throw new IllegalArgumentException("Pretty please enter an int: ");
}
Then someone above you can catch that exception and will have an appropriate error message.
This is obviously a bit awkward which is why it usually isn't used this way.
Note:
You aren't usually supposed to re-use java exceptions but create your own. This is pretty annoying and I almost always re-use either IllegalArgumentException or IllegalStateException Because those are good, reusable exceptions and describe most of the reasons you'd want to throw in general code for "Catch and rethrow" exceptions as I discussed above.

Java: Program crashes after inputting two bad values

I coded a program, that calculates the gcd (greatest common divisor) and lcm (least common multiple). Everything works fine except the try {...} catch(...) {...}. Here is the part of the code that doesn't work as I want it to:
try {
num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
System.out.print("Enter your first number: ");
num1 = Integer.parseInt(sc.nextLine());
}
When I input e.g. letters, it says:
Your input is not an integer (number w/o decimals)! Try again.
Enter your first number:
But when I type letters the second time, the program crashes:
Exception in thread "main" java.lang.NumberFormatException: For input string: "asdf"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at GCDLCMgetter.main(GCDLCMgetter.java:56)
It is probably a very simple mistake I made but I can't figure it out...
Thank you
Your second parseInt method call is not in try catch block. You need to use a loop for this kind of logic.
It's because your second prompt is inside the catch block. Instead of prompting again inside the catch block, you want to wrap the entire code section in a loop so it comes back around to the try block for the prompt again.
Something like:
boolean repeat = true;
while(repeat){
try{
//Prompt for input
repeat = false;
}catch(Exception e) {
//Display error message
}
}
When the first time you give letters it goes into catch block. Displays the error message. And then executes the line num1 = Integer.parseInt(sc.nextLine());
Again you have entered the letters, but this time there is no try-catch block to handle this. So it throws error.
In your code, it gets executed twice:
Reads a Line at try{...}
There is an Exception
The Exception is handled by the catch(Exception e){...}
The num1 = Integer.parseInt(sc.nextLine()); inside the catch(Exception e){...} cannot be handled. It's not placed inside try{}.
Execution finished because the last exception cannot be handled by any catch.
It seems you're using Scanner, I would recommend you using a loop whis way:
while (sc.hasNextLine()){
try {
System.out.print("Enter your first number: ");
num1 = Integer.parseInt(sc.nextLine());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
}
}
If you're managing integers, it would be interesting using Scanner.nextInt()
while (sc.hasNextInt()){
try {
System.out.print("Enter your first number: ");
num1 = sc.nextInt());
}
catch(Exception e) {
System.out.println("Your input is not an integer (number w/o decimals)! Try again.");
}
}

Exceptions. How do I fix that? First steps

few weeks ago I have starded learning java. Im new and I make many mistakes. Today Im trying to learn about exceptions. I wrote a program which compute square of rectangle, but it doesnt works when i put in side "a" for example c letter. I would like if it shows to me string like "We have a problem ;)", but it throws error. Can you help me?
package Learning;
import java.io.*;
import java.util.Scanner;
public class Exceptions {
public static void main(String[] args) throws IOException {
double a,b,wynik;
Scanner odc = new Scanner(System.in);
try {
System.out.println("Enter side a: ");
a = odc.nextDouble();
System.out.println("Enter side b: ");
b = odc.nextDouble();
wynik=a*b;
System.out.println("Field equals: "+wynik);
}
catch(NumberFormatException e){
System.out.println("We have a problem ;)");
}
}
}
When i put in side a, "c" letter i have something like that:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Learning.Exceptions.main(Exceptions.java:11)
I need to see: "We have a problem ;)"
catch the InputMismatchException:
catch(NumberFormatException | InputMismatchException e){ ... }
System.out.println("We have a problem ;)"); will be executed if either a NumberFormatException or InputMismatchException arises.
if you want to output different result based on the exception type then create another catch block for InputMismatchException.
Your code never throw any NumberFormatException.
The impossibility to convert the input to a double is already conveyed by InputMismatchException.
Note that NumberFormatException and InputMismatchException are unchecked exceptions (they derive from RuntimeException).
This kind of exception may be thrown even if these are not declared as thrown by any invoked methods.
So generally you may want to catch them because you know that they may be thrown and you want to handle it.
But you should be aware to catch only them when these may be effectively thrown as it makes code clearer.
Here it is not the case.
So in your case that is enough :
try {
System.out.println("Enter side a: ");
a = odc.nextDouble();
System.out.println("Enter side b: ");
b = odc.nextDouble();
wynik=a*b;
System.out.println("Field equals: "+wynik);
}
catch(InputMismatchException e){
System.out.println("We have a problem ;)");
}

Java - Try/Catch NumberFormatException uses a former value?

First post so my apologies if this was done incorrectly (and am also relatively new to programming, so any extraneous tips are also appreciated).
So I have written up a basic calculator program in Java. It works well currently, but I am having a particular issue with NumberFormatException. Here's the code:
private static double spaceTestAndConvert(String numInput){
Scanner input= new Scanner(System.in);
if (numInput.equalsIgnoreCase("quit")){
System.exit(1);
}
else if(numInput.equalsIgnoreCase("C/E")){
Restart();
}
try{
return Double.parseDouble(numInput.trim());
}
catch(NumberFormatException nfe){
numInput = "";
System.out.println("Please enter only one number without any spaces or letters: ");
numInput = input.nextLine();
spaceTestAndConvert(numInput.trim());
return Double.parseDouble(numInput.trim());
}
}
The issue is that after trying to force an error by entering in several inputs which would cause NumberFormatException and then entering in a valid input, the program will crash from a NumberFormatException citing the previous invalid input.
I.E. -
"1 2 3"
loops back
"1 2 q 3"
loops back
"12q3 3 sqw 1"
loops back
"12"
crash - Exception in thread "main" java.lang.NumberFormatException: For input string: "12q3 3 sqw 1"
It only occurs after several occurrences of the exception. I'm curious why it is doing this. Any advice on how to fix this or explanation of what is happening? If you need any other part of the code, please let me know! Thanks!
I don't follow everything that you're saying, but these 2 lines (from within your catch block) look problematic...
spaceTestAndConvert(numInput.trim());
return Double.parseDouble(numInput.trim());
You are calling the spaceTestAndConvert function recursively, but throwing away the value. I don't understand why you would call it and not be interested in the value.
The second line is also a mess. You so carefully surround the first call to Double.parseDouble() with try/catch, but then you call it again within your catch block. If the second Double.parseDouble() generates a NumberFormatException, it will not be caught.
removing the return in catch will solve your problem. because if you have return on it, you are going to return an invalid Number format since you are in a catch. What you want to do is to return a value when it is now valid, you are now actually doing it inside the try. Don't force your program to return the value with error (since it is in a catch) because it will really give you an error.
returning to previous method after you had the right value (because of recursion) will still have the stack of error value aside from success value you gained from the end part because they are different variables.
private static double spaceTestAndConvert(String numInput){
Scanner input= new Scanner(System.in);
if (numInput.equalsIgnoreCase("quit")){
System.exit(1);
}
else if(numInput.equalsIgnoreCase("C/E")){
Restart();
}
try{
return Double.parseDouble(numInput.trim());
}
catch(NumberFormatException nfe){
numInput = "";
System.out.println("Please enter only one number without any spaces or letters: ");
numInput = input.nextLine();
spaceTestAndConvert(numInput.trim());
}
}

InputMismatchException...even with try/catch

So I'm writing code here just for fun but I've come up with an error that I just can't seem to fix. This block of code is supposed to take in an int... at first i had the hasNextInt() in the while loop alone to try and ensure i'm getting the correct input, but as fate would have it.. i got the exception. I then added a try catch to it thinking maybe i just did something wrong... and still i get the same error. I don't know whats wrong here. this is actually my 1st time using a try catch block (still kind of a noob). it looks good to me and i've looked at the documentation online and done some minor research but to no avail. can anyone identify whats wrong here?
check it out:
do{
System.out.println("How much AP do you want to allocate towards HP? ");
try {//added try catch... still throwing the exception..
while(!in.hasNextInt()){//this should've been enough, apparently not
System.out.println("That is not a valid input, try again.");
in.nextInt();
}
} catch (InputMismatchException e) {
System.out.print(e.getMessage()); //trying to find specific reason.
}
hpInput = in.nextInt();
}while(hpInput < 0 || hpInput > AP);
if i entered a string it would give me the "That is not a valid input, try again." line.. but the exception would still occur right after instead of just looping until an actual int is detected... help plz..
Your while loop should look something like this
while(!in.hasNextInt()){ // <-- is there an int?
System.out.println("That is not a valid input, try again.");
// in.nextInt(); // <-- there is not an int...
in.next(); // <-- this isn't an int.
}
Because the Scanner doesn't have an int.
You can't really validate the value in the Scanner until something has been input, but once it's input, it's too late to validate it...
Instead, you could use a second Scanner to validate the String result you are getting from the user via the keyboard, for example
Scanner kbd = new Scanner(System.in);
int result = -1;
do {
System.out.println("How much AP do you want to allocate towards HP? ");
String value = kbd.nextLine();
Scanner validate = new Scanner(value);
if (validate.hasNextInt()) {
result = validate.nextInt();
}
} while (result < 0);

Categories

Resources