简体   繁体   中英

Java - How do I stop my program to read next line(s) after an “Exception”

I need some help.

When I made a "catch Exception" thing, it wont stop reading more lines. How do I prevent this?

I did like this:

try {
    double1 = Double.parseDouble(args[2]);
} catch (NumberFormatException e) {
    e.printStackTrace();
    user.sendMessage("Can't parse 3rd argument into a number!");
} 
if(double1 > 200 || double1 <= 0) {
user.sendMessage("Error. Nothing special here.");
}

When I get an exception for parsing error, it will continue reading to read the other error prevention method [ if (double > 200 || double 1 <= 0) {} ] and because double1 wasn't a number, it will send out to the user who perform the action another ERROR string.

This is how it looks for the user:

Message: Can't parse 3rd argument into a number!

Message: Error. Nothing special here.

Two error messages, one isn't even supposed to be there. How do I make it so only the first error shows up? So it prevents the 2nd error message?

try {
    double1 = Double.parseDouble(args[2]);

    if (double1 > 200 || double1 <= 0) {
        user.sendMessage("Error. Nothing special here.");
    }
} catch (NumberFormatException e) {
    e.printStackTrace();
    user.sendMessage("Can't parse 3rd argument into a number!");
} 

This works, but it is not a very good design. The NumberFormatException is not properly handled, since you are logging it and then allowing the rest of the code to run. You actually want it to stop the execution and not run the rest of the code (the if condition), so that's what the exception should do - either do an early return or propagate the exception to be handled further up in the stack.

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