简体   繁体   中英

Any Sample code on how to deal with exceptions thrown because of wrong input format?

I am creating a simple calculator that performs simple mathematical operations. I am new to this concept of throwing and catching exceptions. My question is, how do I handle an invalid input? I want to tell the user when their input is invalid and set the result to 0 instead of closing my application. How can I write a try/catch block for that?

else if (btn.getId() == 0x7f050062) {
        double LeftVal = Double.parseDouble(currentInput);
        double result = 0;
        if (currentInputLen > 0 && currentInput != "0") {
            result = Math.asin(LeftVal);
            result *= 180;
            result /= Math.PI;
        }
        inputText.setText(result + "");

This code should calculate sininverse of input value and output the result, but if i set input to 12 and caluclate sininverse(12) it shows NaN. Now, if i perform any other operation on NaN i crashes my application.

You can import java.util.InputMismatchException to your program and include the operation code for your calc inside the try code block and after it catch the InputMismatchException, but I think it's even better to just prompt the user again for new input instead of setting the result to 0. Do you have any code written yet? I could write a small program here for you but I think it would be better for you to share the code you have so far and we can work from that.

Hope this helps.

try
{
  // code here
}
catch(Exception e)
{//code to set value to 0 here}

Hope that helps a little. The try statement will try all the code in the block and if an error happens to be thrown it will go to the catch block doing what code is in there.

EDIT: according to the code you have now posted, I can tell it's not a parsing problem now.

You might want to check for NaN value and then assign 0 and/or tell the user.

If you want to keep going after an error, don't use an exception:

if (result == Double.NaN) {
    System.err.println("Number out of range, expected number in [-1, 1]");
    result = 0;
}

If you want to stop and tell the user to input something else, use an exception:

if (result == Double.NaN) {
    throw IllegalArgumentException();
}

And in your main:

try {

    // the call to the method that raises the exception

} catch (IllegalArgumentException e) {
    System.err.println("Number out of range, expected number in [-1, 1]");
}

ORIGINAL POST:

If you're parsing numbers, then at some point you will probably have to use Integer.parseInt(String) or the equivalent of other number classes. These methods throw a NumberFormatException if the input string is not a number formatted as they expect. You can see it in the doc .

When such an error occurs, the execution will stop and you can do something in the catch block:

double inputNumber;
try {

    // some code

    inputNumber = Double.parseDouble(inputString);

    // here you are sure inputNumber was parsed successfully

} catch (NumberFormatException e) {

    // do something to tell the user about his error (or not)
    System.err.println("wrong input");

    inputNumber = 0;
}

// do something with inputNumber (it is either 0 or the input number here)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM