简体   繁体   English

如何在Java中的try catch语句期间结束程序?

[英]How can I end a program during a try catch statement in Java?

I already asked a question about how to have a message pop up and say "please enter a number input" but it was supposed to end the program. 我已经问了一个有关如何弹出消息并说“请输入数字输入”的问题,但是它应该结束程序。 Not crash it, but end the program then you would have to rerun it. 不要将其崩溃,而是结束程序,然后您必须重新运行它。

`    try 
 {
     number = in.nextInt();

       if(number >= 8) 
       { 
       number = 8; 
       }
       else if (number <= 0)
       {
       number = 0;
       }
   } 
   catch (InputMismatchException exc) 

   {
       System.out.println("Program requires NUMBER input");

   }

` `

I tried doing a "break;" 我试图做一个“休息”; in the catch (experimented I guess) and it didn't work. 在赶上(我猜是实验),它没有用。


UPDATE: Thanks everyone, I tried return in a previous project and it didn't work. 更新:谢谢大家,我尝试返回上一个项目,但没有成功。 But it worked here so thank you again!! 但是它在这里有效,所以再次感谢您!

Use the return statement. 使用return语句。 That should end the method. 那应该结束方法。 System.exit(0) is an alternative option. System.exit(0)是替代选项。 However, you must be cautious when using System.exit(0) because: 但是,使用System.exit(0)时必须谨慎,因为:

The System.exit method forces termination of all threads in the Java virtual machine. System.exit方法强制终止Java虚拟机中的所有线程。 This is drastic....System.exit should be reserved for a catastrophic error exit, or for cases when a program is intended for use as a utility in a command script that may depend on the program's exit code. 这是非常麻烦的。...System.exit应该保留用于灾难性错误退出,或在程序打算用作程序中可能取决于程序退出代码的命令脚本中用作实用程序的情况。

Source: Use System.exit with care 来源: 谨慎使用System.exit

Use System.exit(); 使用System.exit();

   try{
   ...
   } 
   catch (InputMismatchException exc) 

   {
       System.out.println("Program requires NUMBER input");
       System.exit(1);

   }

Or if your are in the main function, you can just return; 或者,如果您在main函数中,则可以return;

Use return; 使用return; , read also What does the return keyword do in a void method in Java? ,也请阅读Java中void方法中的return关键字做什么?

public static void main(String[] args) {

    return; // END OF PROGRAM :)
}

Returning a Value from a Method 从方法返回值

return statement can be used to branch out of a control flow block and exit the method return语句可用于分支出控制流块并退出方法

You can just make use simple return; 您可以使用简单的收益; at end of the catch block rather then System.exit(), it will kill the jvm. 在catch块的末尾而不是System.exit()处,它将杀死jvm。

If you're certain you want the program to terminate you would just do 如果您确定要终止程序,则只需执行

System.out.println("Program requires NUMBER input");
System.exit(1); // <-- non-zero to indicate an error.

If that's in your main method, do return; 如果那是您的main方法,请return; otherwise you can do eg System.exit(1); 否则,您可以执行例如System.exit(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM