你可以在try块内抛出异常并终止程序。

huangapple go评论56阅读模式
英文:

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 &lt; 1 &amp;&amp; m &gt; 12)
    throw new NumberFormatException(m + &quot; luna invalida&quot;);
else if ((m &gt; 8 &amp;&amp; m % 2 != 0 &amp;&amp; d == 31) || (m &lt; 8 &amp;&amp; m % 2 == 0 &amp;&amp; d == 31))
    throw new NumberFormatException(m + &quot; &quot; + d + &quot; luna,zi invalida&quot;);
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.

huangapple
  • 本文由 发表于 2020年5月3日 20:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61574293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定