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 ;)");
}
Related
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.
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());
}
}
I am trying to run a simple code which will take an account number as the long type from the user through nextLong() method.Now if the user has given the account_number(long accNo) as string_type or character_type instead of long_type value then the InputMismatchException is thrown.That is also fine,because I am aware of the fact that nextLong() method can throw InputMismatchException along with NoSuchElementException and IllegalStateException.But after that when I am expecting that after getting InputMismatchException the loop will revisit and ask me to give the account_number(long accNo) as long value again! then the problem occurs.It is not asking me to give any value,instead an infinite loop is running along with the exception again & again.!!
package genericsandcollection;
import java.util.*;
public class ScannerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
boolean b=true;
while(b){
try{
System.out.println("Enter Your Account Number..: ");
long accNo=sc.nextLong();
System.out.println(accNo);
b=false;
}catch(InputMismatchException | IllegalStateException e){
e.printStackTrace();
System.out.println(e);
System.out.println("Wrong syntax");
}
}
}
}
Why is it happening ? Is not nextLong() smart enough to handle a situation inside a loop ! If I use Long.parseLong(sc.next()) instead of sc.nextLong(),then everything is alright as parseLong() is throwing NumberFormatException i.e. until I will give the account number as long_type it keeps asking the user to give the account_number as long_type value.Really Strange !!!! If anybody has any concern,please help.Thank you.
Do not close the scanner in the catch block or you won't be able to use it again.
You shouldn't close the Scanner because as well as meaning you cannot use the Scanner anymore it will also close System.in. Your infinite loop is because using any other method than nextLine will leave a line break (from pressing 'enter' to submit) at the end of the input buffer. This will cause nextLong to always throw an exception.
Calling nextLine will advance the Scanner. The following is a short example that shows this (adapted from a very similar answer I wrote).
do {
try {
accNo = sc.nextLong();
break;
} catch (InputMismatchException e) {
} finally {
sc.nextLine(); // always advances (even after the break)
}
System.out.print("Input must be a number: ");
} while (true);
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
I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.