So I'm trying to parse an numeric input in my EditText box. I'm using Integer parse to parse input into int.
#Override
public void afterTextChanged(Editable s) {
int temp;
try{
temp=Integer.parseInt(s.toString());
//do something
}catch (NumberFormatException e){
temp=someOtherNumber;
}
}
I want to continue app even if user entered invalid number.
Is that possible?
Yes this is possible. Put only catch able code in try catch block. write your remaining code after above catch block.
NumberFormatException you should put when you are confident enough that
1.) Editable s, s is not null. // if not - use Exception class here
If that ius not the case, then catching more prcise exception ie. NumberFormatException is enough. you have already put a catch block, so exception will not be propagated, and you can still continue with your app.
basic Structure
try{
// do your stuff here 1
}catch(NumberFormatException nfe){
// do your stuff here 2
}
// do your stuff here 3
Either do your stuff at 1 and 2 both or just at 3
First check for Editable s it should not null then go further., If you want to catch any exception other than NumberformatException.
then change Catch(NumberFormatException e) to this catch (Exception e). If you have any query please let know.
Related
I have a problem that when I use Integer.parseInt in this context it doesn't convert my and somehow it even kick me out of loop so it dont't want to display for example System.out.print(1) after loop like everything was crashed but i have no error. Please help. That's a part of code which cause it. variable "input" is an Arrayl
for (int i=0;i<input.size();i++)
{
if(point>Integer.parseInt(input.get(i).split(":")[1]))
{
input.set(i,highScore + System.getProperty("line.separator"));
break;
}
}
Have you verified that input.get(i).split(":")[1] gives you exactly a string that only contains digits?
Integer.parseInt(String s) throws NumberFormatException, so you should execute that code inside a try/catch block like this:
for (int i=0;i<input.size();i++) {
try {
int parsedValue = Integer.parseInt(input.get(i).split(":")[1]);
// do whatever you want to do with parsedValue
}
catch(NumberFormatException e) {
System.out.print("I caught an error!, what i was trying to parse wasn't a number");
// or any other action you consideer that needs to be done when parseInt fails
}
}
There is only one explanation (if you are sure that no exception is thrown): the input is empty. :)
I'm looking for an exception on how to catch an invalid String that is user input. I have the following code for a exception on an integer input:
try {
price = Integer.parseInt(priceField.getText());
}
catch (NumberFormatException exception) {
System.out.println("price error");
priceField.setText("");
break;
But I'm not aware of a specific exception for strings, the input is a simple JTextBox so the only incorrect input I can think of is if the user enters nothing into the box, which is what I'm looking to catch.
if (textField.getText().isEmpty())
is all you need.
Or maybe
if (textField.getText().trim().isEmpty())
if you also want to test for blank inputs, containing only white spaces/tabs.
You generally don't use exceptions to test values. Testing if a string represents an integer is an exception to the rule, because there is no available isInt() method in String.
You can do like
if (priceField.getText().isEmpty())
throw new Exception("priceField is not entered.");
You could check if priceField contains a string by using this:
JTextField priceField;
int price;
try {
// Check whether priceField.getText()'s length equals 0
if(priceField.getText().getLength()==0) {
throw new Exception();
}
// If not, check if it is a number and if so set price
price = Integer.parseInt(priceField.getText());
} catch(Exception e) {
// Either priceField's value's length equals 0 or
// priceField's value is not a number
// Output error, reset priceField and break the code
System.err.println("Price error, is the field a number and not empty?");
priceField.setText("");
break;
}
When the if-statement is true (If the length of priceField.getText() is 0) an exception gets thrown, which will trigger the catch-block, give an error, reset priceField and break the code.
If the if-statement is false though (If the length of priceField.getText() is greater or lower than 0) it will check if priceField.getText() is a number and if so it sets price to that value. If it not a number, a NumberFormatException gets thrown, which will trigger the catch-block etc.
Let me know if it works.
Happy coding :) -Charlie
if you want your exception to be thrown during the normal operation of the Java Virtual Machine, then you can use this
if (priceField.getText().isEmpty())
throw new RunTimeException("priceField is not entered.");
I'm learning java and I'm trying to make a very simple application that does conversion of currency. You enter a rate, a direction (e.g : from euro to dollars or reverse) and an amount. the numbers valid non negative numbers.
So far I managed to make it so that the number can't be negative; now I need to throw an error if it's not a number.
I have following code:
public void setKoers(double koers)
throws NegativeValueException, NumberFormatException{
if (koers > 0 ) {
this.koers=koers;
} else {
throw new NegativeValueException("negative number");
}
}
and my main looks like
try {
cal.setKoers( Double.parseDouble(args[0]));
} catch(NegativeValueException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println( e.getMessage());
}
So how can I check if koers is a number or not.
I know I could put try and catch the error in my code, but I think this would go against the logic of where and how to deal with errors: in my main function I should catch any NumberFormatException
You do not need the NumberFormatException since Double.parseDouble() takes care of it for you. If it is not a proper number (in this case a Double) than the parseDouble() method will throw a NumberFormatException for you.
Here's how I would write it: (just take out the NumberFormatException)
public void setKoers(double koers) throws NegativeValueException {
if (koers > 0 ) {
this.koers=koers;
} else {
throw new NegativeValueException("negative number");
}
}
try{
cal.setKoers( Double.parseDouble(args[0]));
} catch(NegativeValueException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println( e.getMessage());
}
You will probably want to validate your input when the user tells the program to accept and process the input. In this portion of the code, you would convert the String to a number by parsing the input within a try/catch block, and then if an exception is encountered, notify the user of the error, prevent further processing, and perhaps clear any offending entry fields if present.
I implemented a circular list in Java. The code asks for the int values to be entered, and I wish to terminate the input list with an "END". The code works but throws a runtime exception: NumberFormatException.
try{
while(true){
newnode=new Node();
oldnode.next=newnode;
newnode.prev=oldnode;
System.out.print("Enter value:");
try{
ctrlstr=bfr.readLine();
}
catch(Exception ex){
ex.printStackTrace();
}
if (ctrlstr=="END") break;
newnode.val=Integer.parseInt(ctrlstr);
oldnode=newnode;
i++;
}
}
catch(Exception ex){
ex.printStackTrace();
}
Here:
if (ctrlstr=="END")
you're comparing strings using ==, which always checks for reference identity. Instead, you should use equals:
if (ctrlstr.equals("END"))
or perhaps (if you want just a false result when ctrlstr is null)
if ("END".equals(ctrlstr))
A few extra notes:
Catching Exception is usually a bad idea - you should catch more specific exceptions
Catching an exception and then continuing anyway after printing it is usually a bad idea
Your code will be more readable if you indent appropriately
Your code will be more readable if you always use braces for if statements etc
Try
ctrlstr.equals("END") instead.
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.