英文:
How can I throw exception inside the try block and terminate the program
问题
try
{
m = Integer.parseInt(data[1]);
if (m < 1 && m > 12)
throw new NumberFormatException(m + " invalid month");
else if ((m > 8 && m % 2 != 0 && d == 31) || (m < 8 && m % 2 == 0 && d == 31))
throw new NumberFormatException(m + " " + d + " invalid month or day");
else
luna = month[m];
} catch (NumberFormatException e)
{
m = 0;
}
英文:
My program takes input from the console as DD/MM/YYYY
representing a date.
I store all the data accordingly.<br> In this try catch block i am checking if variable "m" is a correct month, regarding the day and being between 1 and 12.
If "m" is not a number, the NumberFormatException
is thrown. <br>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.
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;
}
答案1
得分: 1
你应该将Integer.parseInt(data[1])
放在一个try-catch块中,而将其他所有代码放在它的外部。如果你经常使用parseInt
,你可以将转换放在一个函数内。
m = 0;
try {
m = Integer.parseInt(data[1]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
// 其余的代码在这里
英文:
You should have the Integer.parseInt(data[1])
inside a try-catch block but all of the other code outside it. If you're using parseInt
often, you could have the conversion inside a function.
m = 0;
try {
m = Integer.parseInt(data[1]);
} catch (NumberFormatException e)
{
e.printStackTrace();
}
// Rest of the code goes here
答案2
得分: 0
在 catch 块内部。输入以下内容:
System.exit(0);
我在 JavaFX GUI 中使用它。
英文:
Inside the catch block. Type this
System.exit(0).
Im using it in javafx gui.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论