[英]How can I throw exception inside the try block and terminate the program
My program takes input from the console as DD/MM/YYYY
representing a date.我的程序从控制台接受输入作为代表日期的
DD/MM/YYYY
。 I store all the data accordingly.我相应地存储所有数据。
In this try catch block i am checking if variable "m" is a correct month, regarding the day and being between 1 and 12.在这个 try catch 块中,我正在检查变量“m”是否是正确的月份,关于日期并且在 1 到 12 之间。
If "m" is not a number, the NumberFormatException
is thrown.如果“m”不是数字,则抛出
NumberFormatException
。
I want to be able to throw the exceptions inside the if conditions and terminate the program displaying the thrown error and the message associated to it.我希望能够在 if 条件中抛出异常并终止显示抛出的错误和与之关联的消息的程序。
try
{
m = Integer.parseInt(data[1]);
if (m < 1 && m > 12)
throw new NumberFormatException(m + " luna invalida");
else if ((m > 8 && m % 2 != 0 && d == 31) || (m < 8 && m % 2 == 0 && d == 31))
throw new NumberFormatException(m + " " + d + " luna,zi invalida");
else
luna = month[m];
} catch (NumberFormatException e)
{
m = 0;
}
You should have the Integer.parseInt(data[1])
inside a try-catch block but all of the other code outside it.您应该在 try-catch 块内有
Integer.parseInt(data[1])
,但所有其他代码都在它之外。 If you're using parseInt
often, you could have the conversion inside a function.如果您经常使用
parseInt
,您可以在 function 中进行转换。
m = 0;
try {
m = Integer.parseInt(data[1]);
} catch (NumberFormatException e)
{
e.printStackTrace();
}
// Rest of the code goes here
Inside the catch block.在 catch 块内。 Type this
输入这个
System.exit(0).
Im using it in javafx gui.我在 javafx gui 中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.