Java как завершить программу с ошибкой

@gratur asks in a comment on @skaffman’s answer.

So if I understand correctly, I let the exception bubble up by removing the try/catch block and adding a «throws IOException» to that method (and methods that call that method, and so on)? I feel kind of icky doing that, because now I have to add a bunch of «throws IOException»s everywhere — is my ickiness misguided?

I think it depends. If the exception only has to bubble up a small number of levels, and it makes sense for the methods to propagate an IOException, then that’s what you should do. There is nothing particularly «icky» about allowing an exception to propagate.

On the other hand, if the IOException has to propagate through many levels and there is no chance that it might be handled specifically beyond a certain point, you may want to:

  • define a custom ApplicationErrorException that is a subclass of RuntimeException,
  • catch the IOException near its source and throw an ApplicationErrorException in its place … with the cause set of course, and
  • catch the ApplicationErrorException exception in your main method.

At the point in main where you catch the ApplicationErrorException, you can call System.exit() with a non-zero status code, and optionally print or log a stack trace. (In fact, you might want to distinguish the cases where you do and don’t want a stack trace by specializing your «application error» exception.)

Note that we are still allowing an exception to propagate to main … for the reasons explained in @skaffman’s answer.


One last thing that complicates this question is exceptions that are thrown on the stack of some thread other than the main thread. You probably don’t want the exception to be handled and turned into a System.exit() on the other thread’s stack … because that won’t give other threads a chance to shut down cleanly. On the other hand, if you do nothing, the default behaviour is for the other thread to just terminate with an uncaught exception. If nothing is join()-ing the thread, this can go unnoticed. Unfortunately, there’s no simple «one size fits all» solution.

Java – язык программирования, имеющий множество приложений. При программировании для одного из этих приложений вы можете застрять на каком-то этапе этой программы. Что делать в этой ситуации? Есть ли способ выйти в этой самой точке? Если эти вопросы вас беспокоят, вы попали в нужное место.

Что вы можете сделать, это просто использовать метод System.exit(), который завершает текущую виртуальную машину Java, работающую в системе.

Вы можете выйти из функции, используя метод java.lang.System.exit(). Этот метод завершает текущую запущенную виртуальную машину Java (JVM). Он принимает аргумент «код состояния», где ненулевой код состояния указывает на ненормальное завершение.

Если вы работаете с циклами Java или операторами switch, вы можете использовать операторы break, которые используются для прерывания / выхода только из цикла, а не всей программы.

Что такое метод System.exit()?

Метод System.exit() вызывает метод exit в классе Runtime. Это выходит из текущей программы, завершая виртуальную машину Java. Как определяет имя метода, метод exit() никогда ничего не возвращает.

Вызов System.exit (n) фактически эквивалентен вызову:

Runtime.getRuntime().exit(n)

Функция System.exit имеет код состояния, который сообщает о завершении, например:

  • выход (0): указывает на успешное завершение.
  • выход (1) или выход (-1) или любое ненулевое значение – указывает на неудачное завершение.

Исключение: выдает исключение SecurityException.

Примеры

package Edureka;

import java.io.*;
import java.util.*;

public class ExampleProgram{

public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int i = 0; i < arr.length; i++) { if (arr[i] >= 4)
{
System.out.println("Exit from the loop");

System.exit(0); // Terminates JVM
}
else
System.out.println("arr["+i+"] = " +
arr[i]);
}
System.out.println("End of the Program");
}
}

Выход: arr [0] = 1 arr [1] = 2 arr [2] = 3 Выход из цикла

Объяснение: В приведенной выше программе выполнение останавливается или выходит из цикла, как только он сталкивается с методом System.exit(). Он даже не печатает второй оператор печати, который говорит «Конец программы». Он просто завершает программу сам.

Пример 2:

package Edureka;

import java.io.*;
import java.util.*;

public class ExampleProgram{

public static void main(String[] args)
{
int a[]= {1,2,3,4,5,6,7,8,9,10};
for(int i=0;i<a.length;i++)
{
if(a[i]<=4)
{
System.out.println("array["+i+"]="+a[i]);
}
else
{
System.out.println("Exit from the loop");
System.exit(0); //Terminates jvm
}
}
}
}

Вывод: array [0] = 1 array [1] = 2 array [2] = 3 array [3] = 4 Выход из цикла

Объяснение: В приведенной выше программе она печатает элементы до тех пор, пока условие не станет истинным. Как только условие становится ложным, оно печатает оператор и программа завершается.

What’s the best way to quit a Java application with code?

Kara's user avatar

Kara

6,08516 gold badges49 silver badges57 bronze badges

asked Apr 19, 2010 at 21:15

Olaseni's user avatar

2

You can use System.exit() for this purpose.

According to oracle’s Java 8 documentation:

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

Community's user avatar

answered Apr 19, 2010 at 21:16

Jonathan Holloway's user avatar

Jonathan HollowayJonathan Holloway

61.8k32 gold badges125 silver badges150 bronze badges

0

System.exit(0);

The «0» lets whomever called your program know that everything went OK. If, however, you are quitting due to an error, you should System.exit(1);, or with another non-zero number corresponding to the specific error.

Also, as others have mentioned, clean up first! That involves closing files and other open resources.

answered Apr 19, 2010 at 21:20

Chris Cooper's user avatar

Chris CooperChris Cooper

17.2k9 gold badges52 silver badges70 bronze badges

2

System.exit(int i) is to be used, but I would include it inside a more generic shutdown() method, where you would include «cleanup» steps as well, closing socket connections, file descriptors, then exiting with System.exit(x).

Kevin's user avatar

Kevin

4,6023 gold badges38 silver badges61 bronze badges

answered Apr 20, 2010 at 1:55

Bastien's user avatar

BastienBastien

1,5372 gold badges10 silver badges19 bronze badges

System.exit() is usually not the best way, but it depends on your application.

The usual way of ending an application is by exiting the main() method. This does not work when there are other non-deamon threads running, as is usual for applications with a graphical user interface (AWT, Swing etc.). For these applications, you either find a way to end the GUI event loop (don’t know if that is possible with the AWT or Swing), or invoke System.exit().

answered Apr 19, 2010 at 21:20

Christian Semrau's user avatar

Christian SemrauChristian Semrau

8,8532 gold badges32 silver badges39 bronze badges

Using dispose(); is a very effective way for closing your programs.

I found that using System.exit(x) resets the interactions pane and supposing you need some of the information there it all disappears.

Kevin's user avatar

Kevin

4,6023 gold badges38 silver badges61 bronze badges

answered Jun 17, 2011 at 3:37

Joshua's user avatar

I agree with Jon, have your application react to something and call System.exit().

Be sure that:

  • you use the appropriate exit value. 0 is normal exit, anything else indicates there was an error
  • you close all input and output streams. Files, network connections, etc.
  • you log or print a reason for exiting especially if its because of an error

answered Apr 19, 2010 at 21:20

Freiheit's user avatar

FreiheitFreiheit

8,3306 gold badges59 silver badges101 bronze badges

The answer is System.exit(), but not a good thing to do as this aborts the program. Any cleaning up, destroy that you intend to do will not happen.

answered Apr 20, 2010 at 5:22

Vaishak Suresh's user avatar

Vaishak SureshVaishak Suresh

5,71510 gold badges41 silver badges65 bronze badges

There’s two simple answers to the question.

This is the «Professional way»:

//This just terminates the program.
System.exit(0);

This is a more clumsier way:

//This just terminates the program, just like System.exit(0).
return;

answered Jul 27, 2015 at 18:07

Anton's user avatar

AntonAnton

354 bronze badges

1

Runtime.getCurrentRumtime().halt(0);

answered Oct 5, 2012 at 17:57

Dude Bro's user avatar

Dude BroDude Bro

1,1521 gold badge10 silver badges13 bronze badges

3

System.exit() will do what you want. But in most situations, you probably want to exit a thread, and leave the main thread alive. By doing that, you can terminate a task, but also keep the ability to start another task without restarting the app.

answered Oct 13, 2017 at 0:12

SmartFingers's user avatar

System.exit(ABORT);
Quit’s the process immediately.

answered Apr 22, 2014 at 12:35

pooploser0110's user avatar

1

This should do it in the correct way:

mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowListener() {

@Override
public void windowClosing(WindowEvent e) {
    if (doQuestion("Really want to exit?")) {
      mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainFrame.dispose();
    }
}

answered Oct 14, 2015 at 8:43

user3596517's user avatar

Ответы

Аватар пользователя Сергей Якимович

Прервать выполнение программы можно вызвав System.exit().

Передав в качестве аргумента 0, мы дадим команду на завершение без ошибки. А передав любое ненулевое число N — команду на завершение с ошибкой номер N :

System.exit(0); // завершение без ошибки
System.exit(1); // завершение c ошибкой 1

Вызов return из головного метода main также приведет к завершению программы.



0



0

Добавьте ваш ответ

Рекомендуемые курсы

11 часов

Старт в любое время

69 часов

Старт в любое время

35 часов

Старт в любое время

Похожие вопросы

Метод System.exit() используется в языке Java для завершения программы. Этот метод на вход принимает значение типа int. Обычно это 0, что говорит о том, что программа завершается без ошибок. Любое другое значение говорит о том, что программа завершилась с ошибкой. 

Рассмотрим пример:

public class SysExit {
    public static void main(String[] args) {
        System.out.println("Дo возврата.");
        method(true);
        System.out.println("Этот оператор выполняться не будет.");
    }

    public static void method(boolean flag) {
        if (flag) {
            System.exit(0);
        }
        System.out.println("Этот оператор метода выполняться не будет.");
    }
}

Результат выполнения программы:

Дo возврата.

Презентацию с видео можно скачать на Patreon.

Понравилась статья? Поделить с друзьями:
  • Java virtual machine launcher ошибка как исправить майнкрафт
  • Java virtual machine launcher ошибка как исправить tlauncher
  • Java virtual machine launcher ошибка как исправить minecraft
  • Java virtual machine launcher ошибка error unable to access
  • Java virtual machine launcher ошибка a java exception has