Java System.exit(1) 并返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20887829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:01:49  来源:igfitidea点击:

System.exit(1) and return

javaerror-handlingtry-catch

提问by stumped

import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class CreateTextFile
{
    private Formatter formatter;

    public void openFile()
    {
        try
        {
            formatter = new Formatter("clients.txt");
        }

        catch (SecurityException securityException)
        {
            System.err.println("You do not have permission to access this file");
            System.exit(1);
        }

        catch (FileNotFoundException fileNotFoundException)
        {
            System.err.println("Error opening or creating the file");
            System.exit(1);
        }
    }

    public void addRecords()
    {
        AccountRecord accountRecord = new AccountRecord();
        Scanner scanner = new Scanner(System.in);

        System.out.printf("%s%n%s%n%s%n%s%n", "To terminate input, type the end-of-file indicator", "when you are prompted to enter input", "On Unix/Linux/Mac OS X type <control> d then press Enter", "On Windows type <ctrl> z then press Enter");

        while (scanner.hasNext())
        {
            try
            {
                accountRecord.setAccountNumber(scanner.nextInt());
                accountRecord.setFirstName(scanner.next());
                accountRecord.setLastName(scanner.next());
                accountRecord.setBalance(scanner.nextDouble());

                if (accountRecord.getAccountNumber() > 0)
                    formatter.format("%d %s %s %,.2f%n", accountRecord.getAccountNumber(), accountRecord.getFirstName(), accountRecord.getLastName(), accountRecord.getBalance());
                else
                    System.out.println("Account number must be greater than 0");
            }

            catch (FormatterClosedException formatterClosedException)
            {
                System.err.println("Error writing to file");
                return;
            }

            catch (NoSuchElementException noSuchElementException)
            {
                System.err.println("Invalid input. Try again");
                scanner.nextLine();
            }

            System.out.printf("%s %s%n%s", "Enter account number (>0),", "first name, last name and balance.", "?");
        }
        scanner.close();
    }

    public void closeFile()
    {
        if (formatter != null)
            formatter.close();
    }
}

I was just wondering why in openFile()the catchblocks are terminated with System.exit()and the catchblocks in addRecords()terminate with return. Is there a recommended way of when each should be used?

我只是想知道为什么在openFile()catch块被终止System.exit()catchaddRecords()与终止return。是否有推荐的方法来使用每个方法?

采纳答案by TypeIA

They do different things. returnsimply returns from the function to its caller and the program continues running. System.exit()terminates the program; control does not return to the caller.

他们做不同的事情。return简单地从函数返回给它的调用者,程序继续运行。System.exit()终止程序;控制权不会返回给调用者。

You should use System.exit()when your program encounters an unrecoverableerror and there is no point in the program continuing to run. Use returnwhen your program can gracefully recover, or when the program should perform cleanup/closeout actions before exiting.

System.exit()当您的程序遇到不可恢复的错误并且程序继续运行没有意义时,您应该使用。使用return时,您的程序可以正常恢复,或者当程序在退出前执行清理/收尾动作。

See also this more extended discussion of System.exit().

另见本的更广泛的讨论System.exit()

回答by Joop Eggen

The returnshould have been a break, just leaving the while-loop, so that scanner.close()is done.

return应该是一个break,刚刚离开while循环,这样scanner.close()就完成了。

System.exitis bad style, but feasible for a command line program. Not catching the exception would be somewhat the same: termination with a message, but then with a stack trace too. In this letting the function throw an exception would be the preferable way.

System.exit风格不好,但对于命令行程序是可行的。不捕获异常会有点相同:用消息终止,但也用堆栈跟踪。在这种情况下,让函数抛出异常将是更可取的方式。

回答by Vinay Guru

returnstatement is used inside a method to come out of it.System.exit(0)is used in any method to come out of program. System.exit(0)terminates the program narmally.Whereas System.exit(1)terminates the program because of some error encountered in the program.

return语句在方法内部使用以退出它。System.exit(0)用于任何方法中以退出程序。 System.exit(0) 以正常方式终止程序。而System.exit(1)由于程序中遇到某些错误而终止程序。

回答by Hemin

System.exit()terminates the program at the line of invocation. System.exit(1)terminates the program if an error occurs.

System.exit()在调用行终止程序。 System.exit(1)如果发生错误,则终止程序。