抛出的异常是否可以在执行其他任何内容之前先运行?

huangapple 未分类评论43阅读模式
英文:

Is there a way to make thrown exceptions run first before anything else is executed?

问题

这是我的代码输出:

	[打开文件并检测重复序列号的数量...]

--------- [程序终止] 文件已保存并关闭。 -----------

		== 感谢使用货船信息校正 == - 文件找不到:noduplicate(没有该文件或目录)

正如您所看到的,最后部分 "文件找不到:等等..." 的位置很奇怪。它应该在 "打开文件和程序终止" 之间,而且在我的代码中也是这样放置的。然而,当我运行我的代码时,由于异常处理较慢,所以每次运行代码时,它们可能出现在不同的位置,而不是正确的位置。

是否有什么方法可以解决这个问题?

如果需要实际的代码,这是其中的一部分:

System.out.println("\n\t[打开文件并检测重复序列号的数量...]\n");
		try {
			// 计算文件中对象的数量
			int count = cargosCount(initialCargo);
			
			if (count <= 1) {
				System.out.println("\t[终止程序 - 文件 \"" + initialCargo + "\" 没有重复的序列号,一切正常!]\n");
			}
			else {
// 等等...

然后在 try 块的 finally 子句中,我有 "终止" 消息打印出来。

**编辑:感谢您的评论,我找到了解决方法,必须在与我的消息相同的打印中打印出错误消息:
System.err.println("- 文件找不到:" + e.getMessage() + "\n");

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

		catch (InputMismatchException e) {
			System.err.println("请输入有效的输入。");
		}
		catch (IOException e) {
			System.out.println("[IOException 错误] 堆栈跟踪:");
			e.printStackTrace();
		}
		finally {
			System.out.print("--------- [程序终止] 文件已保存并关闭。 -----------"
					+ "\n\n\t== 感谢使用货船信息校正 ==");
			read.close();
		}

在这段代码中,我的 InputMismatchException 在 finally 子句之后被打印出来...

英文:

Here is the output of my code

	[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)

As you can see, the very last part, "file could not be found: etc.." is oddly placed. It should be between Opening file and Program terminated, and in my code it is placed as such. However, when I run my code, it seems because exception handling are slower, so everytime I run my code, they may appear in different places instead of the right place.

Is there any way around this?

For the actual code if needed, here is the part:

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

Then in the finally-clause of the try-block, I have the "terminated" message printed out.

**EDIT: Thanks for commenting, I found a way to fix it, had to print the error message in the same print as my own message:
System.err.println(&quot;- File could not be found: &quot; + e.getMessage() + &quot;\n&quot;);

**Re-EDIT: actually, problem still occurs in another way:

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

In this code, my InputMismatchException is printed after the finally-clause...

答案1

得分: 0

这是发生的原因是因为e.printStackTrace()会输出到标准错误流(System.err),而您的其他消息会输出到标准输出流(System.out)。这是默认设置,可以更容易地将错误消息路由到与常规输出(例如日志文件)不同的位置。

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

e.printStackTrace(System.out);

运行下面的简化示例,并注意算术异常错误消息可靠地在"Message 2"之后打印。

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...");
        }
    }
}
英文:

This is happening because e.printStackTrace() prints to the standard error stream (System.err), while your other messages are printed to the standard output stream (System.out). This is done by default to make it easier to route error messages to a different log file (for example) than regular output.

If you need regular messages and error messages to appear in sequence, you need to send them to the same output stream. You can do that by calling System.err.println for regular messages (NOT recommended) or by passing the standard output stream reference to the printStackTrace method.

e.printStackTrace(System.out);

Run the simplified example below, and note that the ArithmeticException error message is reliably printed after Message 2.

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

huangapple
  • 本文由 发表于 2020年7月27日 02:08:34
  • 转载请务必保留本文链接:https://java.coder-hub.com/63103887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定