java errorhandling: how to check for numberformatexceptions - java

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.

Related

Catch block in Java code gets executed even when the try block satisfies the mentioned condition?

I am new to Java and I tried to use exceptions in my Java code to give the user an alert if in case he/she types a negative number or a non-numerical value in the text field. But still, when I enter a single-digit positive number, the catch blocks get executed.
//textfield to enter the amount of Rs.
txt_rupees = new JTextField();
//KeyListener to check if the content entered in the text field is a number or not.
txt_rupees.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
try {
//convert the user input in the textfield from string to double
double check = Double.parseDouble(txt_rupees.getText());
//checking if the number entered by the user is positive or not.
if (check > 0) {
lb_check1.setText(" ");
}
else {
lb_check1.setText("Please enter a valid number");
}
}
catch (NumberFormatException ne){
//If the user enters a non-numerical character then this message should be displayed by the label.
lb_check1.setText("ALERT: Please enter a valid float or int value in the textfield");
}
}
});
To understand how try-catch block work, I will give an example.
class InsufficientMoneyException extends Exception{
InsufficientMoneyException(int money){
System.out.println("You only have $"+money);
}
}
class A throws InsufficientMoneyException{
try{
int money = 100;
if(money<1000) throw new InsufficientMoneyException(money);
System.out.println("I am NOT being executed!");
} catch (InsufficientMoneyException e){System.out.println("I am being executed!");}
}
Code block will get executed unless it encounters a statement that tells it to throw a exception. After throwing the exception, the catch will catch the exception and the catch block will get executed.
In your case,
double check = Double.parseDouble(txt_rupees.getText());
The library function parseDouble() will throw the NumberFormatException so the lines in try block after this line, won't get executed.

java-how to handle runtime errors?

I'm writing a java program that adds two numbers with any length(the input is string). it works well but the judge gives me 44 because it has "Runtime Error"
what should i do?
To Answer your question "How to handle runtime-errors",
It is not different from any other exception:
try {
someCode();
} catch (RuntimeException ex) {
//handle runtime exception here
}
This judge may have given you a 44 (assuming that is low) because the input that comes to you as strings may not be numbers at all, and if this happens, your program should not crash? That would be my guess
UPDATE: Now that you have some code up, this is most likely the case, what happens if String a is "hello" ? Your program would crash at Long.parseLong(), you need to handle this!
Replace all your calls to Long.parseLong, by calls to such a method :
private long checkLong(String entry){
long result = 0;
try
{
result = Long.parseLong(entry);
}
catch(NumberFormatException e)
{
System.out.println("Value " + entry + " is not valid") ;
System.exit(1);
}
return result;
}

Continue Android app after checked exception is thrown

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.

Java - looping in try-catch block

I am working on writing a file reader, and the idea is to have the user enter a number that represents the line number from the text file. The variable that holds this number is of type int. However, when the user enters a String instead, Java throws the InputMismatchException exception, and what I want is to have a loop in the catch clause, where I will be looping until the user enters a valid value, i.e. an int. The skeleton looks like this:
public void _____ throws IOException {
try {
// Prompting user for line number
// Getting number from keyboard
// Do something with number
} catch (InputMismatchException e) {
// I want to loop until the user enters a valid input
// When the above step is achieved, I am invoking another method here
}
}
My question is, what are some possible techniques that could do the validation?
Thank you.
while(true){
try {
// Prompting user for line number
// Getting number from keyboard
// Do something with number
//break;
} catch (InputMismatchException e) {
// I want to loop until the user enters a valid input
// When the above step is achieved, I am invoking another method here
}
}
Avoid using exceptions for flow control. Catch the exception, but only print a message. Also, do need for loops within loops.
It's as simple as this:
public void _____ throws IOException {
int number = -1;
while (number == -1) {
try {
// Prompt user for line number
// Getting number from keyboard, which could throw an exception
number = <get from input>;
} catch (InputMismatchException e) {
System.out.println("That is not a number!");
}
}
// Do something with number
}
You can avoid the Exception
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
String input = sc.nextLine();
if (isNumeric(input) {
// do something
// with the number
break; // break the loop
}
}
The method isNumeric:
public static boolean isNumeric(String str) {
return str.matches("^[0-9]+$");
}
If you want use a dialog for input number:
String input = JOptionPane.showInputDialog("Input a number:"); // show input dialog

Java Try and catch

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.

Categories

Resources