System.exit(1) and return

12
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();
    }
}
我只是想知道为什么在openFile()中的catch块被终止时会使用System.exit(),而在addRecords()中的catch块终止时会使用return。是否有建议在何时使用每个的方式?
4个回答

15

它们有不同的作用。 return 只是从函数返回到调用者,程序继续运行。而System.exit()会终止程序,控制权不会返回给调用者。

当你的程序遇到无法恢复的错误且程序没有继续运行的必要时,应该使用System.exit()。当程序可以优雅地恢复正常运行,或者程序在退出之前需要执行清理/关闭操作时,请使用return

还可以参考这个更详细的关于System.exit()的讨论


3
从技术上讲,如果需要进行最终清理,方法应该抛出异常,但是这个答案不错。 - Mad Physicist

1
"return" 应该改为 "break",这样就可以离开 while 循环并执行 "scanner.close()"。
"System.exit" 不是好的编程风格,但对于命令行程序来说是可行的。不捕获异常会有些相似:终止并显示一条消息,但同时也会显示堆栈跟踪信息。在这种情况下,让函数抛出异常是更可取的方式。"

0

return语句用于在方法内部退出该方法。System.exit(0)用于在任何方法中退出程序。 System.exit(0)正常终止程序。而System.exit(1)是因为程序遇到错误而终止程序。


-3

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接