有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在try块中抛出异常并终止程序

我的程序从控制台获取表示日期的DD/MM/YYYY输入。 我相应地存储所有数据
在这个try-catch块中,我检查变量“m”是否是正确的月份,关于日期,介于1和12之间

如果“m”不是数字,则抛出NumberFormatException
我希望能够在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;
}

共 (2) 个答案

  1. # 1 楼答案

    您应该将Integer.parseInt(data[1])放在try-catch块中,但所有其他代码都放在它之外。如果您经常使用parseInt,则可以在函数中进行转换

    m = 0;
    try {
        m = Integer.parseInt(data[1]);
    } catch (NumberFormatException e)
    {
        e.printStackTrace();
    }
    
    // Rest of the code goes here
    
  2. # 2 楼答案

    在挡块里面。打这个

          System.exit(0).
    

    我在JavaFXGUI中使用它