如果断言失败则让java程序退出
我正在开发一个多线程 Java 程序,在整个代码中使用不同的断言,并使用 ea 标志运行我的程序。
当任何断言失败时,我可以让我的程序立即停止并退出吗?
I'm developing a multi-threaded Java program use different assertions throughout the code and run my program using the ea
flag.
Can I make my program immediately stop and exit when any assertion fails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也启用断言。
但必须小心。
enable assertion also.
but it must be taken care.
假设 AssertionError 未被捕获,Assert 将停止任何抛出断言的线程。尽管我认为杀死该线程就足够了,并且您不想去杀死整个程序。无论如何,要真正杀死整个程序,只需用 a 包装您的可运行程序,
这将在引发断言时杀死程序。
因此,您可以创建一个“CrashOnAssertionError”可运行对象来包装所有可运行对象:
然后您可以执行以下操作:
Assert will stop whatever thread threw the assertion, assuming the AssertionError isn't caught. Although I would think that killing that thread would be enough and you wouldn't want to go and kill the whole program. Anyhow, to actually kill the entire program, just wrap your runnables with a
which will kill the program when the assertion is raised.
So you could make a "CrashOnAssertionError" runnable to wrap all of your runnables:
And then you can do something like:
启用断言后,它们会在失败时抛出
java.lang.AssertionError
。只要您不尝试捕获此异常,抛出异常的线程就会在断言失败时停止。如果您想要任何其他行为,可以
catch (AssertionError)
并在catch
语句中执行您想要的任何操作。例如,调用System.exit(1)
。如果您希望
AssertionError
包含错误消息,则需要使用assert Expression1 : Expression2;
形式的断言。有关详细信息,请阅读本文。When assertions are enabled, they throw a
java.lang.AssertionError
upon failing. As long as you don't try to catch this, the thread throwing the exception will stop when an assertion fails.If you want any other behavior, you can
catch (AssertionError)
and do whatever you want inside thecatch
statement. For example, callSystem.exit(1)
.If you want
AssertionError
to include an error message, you need to use theassert Expression1 : Expression2;
form of assert. For more information, read this.