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
285 views
in Technique[技术] by (71.8m points)

java - Why we don't have to add try-catch to a RuntimeException?

I want to ask why we don't have to add try-catch block to a RuntimeException while we should do that with other exceptions?

I mean like :

public class Main {
    public static void main(String[] args) {
       throw new RuntimeException();
    }
}

Edit : when I say : throw new RuntimeException(); it is so clear that there is an exception will happen ,so why the compiler doesn't forbid that ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

That's because it's an unchecked exception. It doesn't need to be explicitly declared or catched. Also see the Java tutorial on the subject.

In general, you should only throw a RuntimeException (preferably one of its "Direct Known Subclasses" listed in the javadoc) to signal that the caller is doing it wrong. E.g. when the caller incorrectly passes a null argument (then throw NullPointerException), or an illegal argument (then throw IllegalArgumentException), or when the caller invokes the method at the wrong moment/state (then throw IllegalStateException), etcetera. The caller is supposed to fix their code to avoid that. E.g. checking beforehand if the argument is not null, or if the argument is in correct format/syntax, or ensuring that the method is called at the right moment.

If there is a specific situation which should throw a runtime exception and you can't use one of its specific subclasses, then you are supposed to extend it and document it properly in the new exception's javadoc and in the calling method, e.g. ConfigurationException extends RuntimeException for the case that the calling code hasn't configured the application/API properly before use. This should signal the enduser (the other developer) sufficiently to take action accordingly.

In a nutshell:

  • RuntimeExceptions should identify programmatically recoverable problems which are caused by faults in code flow or configuration under control of code developer (read: developer's faults).
  • Checked Exceptions should identify programmatically recoverable problems which are caused by unexpected conditions outside control of code developer (e.g. database down, file I/O error, wrong enduser input, etc).
  • Errors should identify programmatically unrecoverable problems outside control of code developer (e.g. out of memory, exception inside an initializer, etc).

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

...