有没有办法让抛出的异常先执行然后再执行其他操作?

时间:2020-07-26 18:08:34

标签: java exception

这是我的代码的输出

    [Opening file and detecting number of duplicate serial numbers...]

--------- [Program terminated] Files having been saved and closed. -----------

        == Thank you for using Cargoship Info Correction == - File could not be found: 
noduplicate (No such file or directory)

如您所见,最后一部分,“找不到文件:等。”很奇怪。它应该在打开文件和程序终止之间,并且在我的代码中就这样放置。但是,当我运行我的代码时,似乎是因为异常处理的速度较慢,所以每次我运行我的代码时,它们可能会出现在不同的位置,而不是正确的位置。

有什么办法解决吗?

如果需要的话,下面是实际代码:

System.out.println("\n\t[Opening file and detecting number of duplicate serial numbers...]\n");
        try {
            //counting number of objects in file
            int count = cargosCount(initialCargo);
            
            if(count <= 1) {
                System.out.println("\t[Terminating program - File \"" + initialCargo + "\" has no duplicated serial number, all is well!]\n");
            }
            else {
etc...

然后在try块的最后一个子句中,我打印了“终止”消息。

**编辑:感谢您的评论,我找到了一种解决它的方法,必须将错误消息与我自己的消息打印在同一张纸上: System.err.println("- File could not be found: " + e.getMessage() + "\n");

**重新编辑:实际上,问题仍然以另一种方式出现:

        catch (InputMismatchException e) {
            System.err.println("Please enter a valid input.");
        }
        catch (IOException e) {
            System.out.println("[IOException error] Stack Trace:");
            e.printStackTrace();
        }
        finally {
            System.out.print("--------- [Program terminated] Files having been saved and closed. -----------"
                    + "\n\n\t== Thank you for using Cargoship Info Correction ==");
            read.close();
        }

在这段代码中,我的InputMismatchException打印在最终条款之后。

1 个答案:

答案 0 :(得分:0)

之所以会这样,是因为e.printStackTrace()打印到标准错误流(System.err),而您的其他消息也打印到标准输出流(System.out)。默认情况下,这样做是为了使将错误消息路由到不同于常规输出的其他日志文件(例如)更容易。

如果需要常规消息和错误消息顺序显示,则需要将它们发送到同一输出流。您可以通过调用常规消息的System.err.println(不推荐)或将标准输出流引用传递给printStackTrace方法来实现。

e.printStackTrace(System.out);

运行下面的简化示例,并注意在消息2之后可靠地打印了ArithmeticException错误消息。

public class Printer {
    public static void main(String[] args) {
        System.out.println("Message 1...");
        
        try {
            System.out.println("Message 2...");
            int x = 10 / 0;
        }
        catch (Exception e) {
            e.printStackTrace(System.out);
            System.out.println("Message 3...");
        }
        finally {
            System.out.println("Message 4...");
        }
    }
}