[英]What exactly do Stopself()? What's the best way to terminate a service running?
[英]What's the best way to terminate a program on error?
在捕获异常并在主函数中处理它之后,您认为关闭程序的最佳方法是什么?
别的东西
public static List<String> readFile(String file) throws NoSuchFileException, EOFException, IOException { Path p = Paths.get(file); if (!Files.exists(p)) { throw new NoSuchFileException(file); } else if (!Files.isRegularFile(p)) { throw new NoRegularFileException(file); } else if (!Files.isReadable(p)) { throw new AccessDeniedException(file); } else if (Files.size(p) == 0) { throw new EOFException(file); } return Files.readAllLines(p); } public static void main(String[] args) { try { if (args.length != 2) { System.out.println("The proper use is: java MyProgram file1.txt file2.txt"); return; } List<List<String>> files = new ArrayList<>(); for (String s : args) { try { files.add(Utilities.readFile(s)); } catch (NoSuchFileException e) { System.out.printf("File %s does not exist%n", e.getMessage()); System.exit(-1); } catch (NoRegularFileException e) { System.out.printf("File %s is not a regular file%n", e.getMessage()); throw e; } catch (AccessDeniedException e) { System.out.printf( "Access rights are insufficient to read file %s%n", e.getMessage() ); throw new ReadFileException(e); } catch (EOFException e) { System.out.printf("File %s is empty%n", e.getMessage()); throw new RuntimeException(e); } } //some other code } catch (Exception e) { e.printStackTrace(); }
编辑:我应该说清楚在 main 结束之前程序中会有一些其他代码,所以我不能让它完成。
如果您希望它干净(即不向用户显示堆栈跟踪),那么抛出异常是不可能的(至少在 main 之外)。 然后是关于是否要从程序返回退出代码,如果不是。
如果要返回退出代码,则必须使用System.exit(int errcode);
. 否则,您可以返回(或让main
正常退出)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.