简体   繁体   English

如何在 try 块内引发异常并终止程序

[英]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.

相关问题 如何在 Try/Catch 块内抛出异常? - How to throw an Exception inside a Try/Catch block? 抛出异常并且不终止Java中的程序 - Throw exception and NOT terminate program in java 在Java中,如何使用在程序其他位置的try / catch块内初始化的变量? - In Java, how can I use a variable initialized inside a try/catch block elsewhere in the program? 如何抛出不会终止程序的IllegalArgumentException? - How do I Throw an IllegalArgumentException that won't terminate my program? 在Main函数中,try块引发异常后,如何使其继续执行下一个try块 - In Main function, after a try block throws an exception how can I make it keep on execute the next try block 如何从外部块中重新抛出lambda块中的异常? - How can I re-throw an exception in a lambda block as from the outer block? Try Catch 块后抛出异常 - Throw Exception after Try Catch block 如何在 UML 序列图中用 SQLException throw 表示 try catch 块? - How can I represent try catch block with SQLException throw in UML sequence diagram? Java:如何在try catch体内向方法调用者抛出异常? - Java: How to throw an Exception to the method caller inside a try catch body? 如何检索&#39;try&#39;块中的抑制异常? - how can suppressed exception in the 'try' block be retrieved?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM