Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

java - System.exit(num) or throw a RuntimeException from main?

I've got a single threaded app that should set the DOS errorlevel to something non-zero if there is a problem. Is it better to throw a RuntimeException, or to use System.exit(nonzero)? I don't need the stack trace, and I don't expect this app to be extended/reused. What are the differences between these two options?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't throw an exception unless you really have an exceptional condition. System.exit(int) is there for precisely this reason. Use it.

EDIT: I think I may have misread your question. I thought you were asking, when you want to exit the JVM normally but signal that something did not quite go right, whether it is better to throw an exception or to use System.exit.

However, if the problem that occurs is something which is already indicated by a Java exception, it's fine to just let that exception go unhandled. You don't have to catch the exception and call System.exit.

If you have a choice of whether to throw an exception of your own or call System.exit, think about whether the error condition is something that might conceivably be handled by some Java code that calls your method. If the error occurs directly in the main method, then there will probably never be a caller to handle the exception so you should probably call System.exit. Otherwise, it's generally best to throw an exception - but not RuntimeException, you should probably use an exception type that appropriately represents the error you encountered. Write your own subclass of RuntimeException if necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...