Is there a safe, programmatic way to determine if it's safe to open a Swing window?

前端 未结 2 618
离开以前
离开以前 2021-01-19 21:38

I have a java app that the user might invoke from the command line by running java -jar app.jar or from a desktop environment by double-clicking the .jar file.

I wo

相关标签:
2条回答
  • 2021-01-19 21:57

    I could just try...catch the InternalError and run the command-line interface in that case, but I'd heard that one shouldn't catch Errors because they might leave the JVM in an inconsistent state. (Please correct me if I'm wrong.)

    Your understanding is half right.

    It is a bad idea to catch an Error and attempt to recover / continue running because the JVM could (already) be in a state from which recovery is not possible.

    However, catching a specific error, printing an informative diagnostic to the console and immediately exiting the JVM is a pretty safe thing to do. (The System.out / err streams are pretty resilient to most things that cause an Error being thrown.)

    In this particular case, there's probably nothing you could do to recover. So bailing out is the most sensible option anyway. (Calling isHeadless() before you attempt to start the GUI is a better idea though.)

    0 讨论(0)
  • 2021-01-19 22:20

    You can use GraphicsEnvironment.isHeadless()

    0 讨论(0)
提交回复
热议问题