[英]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. 当我得到解析错误的异常时,它将继续读取以读取其他错误预防方法[if(double> 200 || double 1 <= 0){}]并且因为double1不是数字,它将发送出去给执行该操作的用户另一个ERROR字符串。
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. NumberFormatException
未正确处理,因为您正在记录它,然后允许其余代码运行。 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. 你实际上希望它停止执行而不运行其余代码(
if
条件),这就是异常应该做的事情 - 要么提前返回,要么传播异常以便在堆栈中进一步处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.