且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们不必为RuntimeException添加try-catch?

更新时间:2023-11-29 15:21:34

这是因为它是一个未选中的异常。它不需要被明确声明或捕获。另请参阅有关此主题的Sun教程

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

更新:一般来说,您只应该抛出一个 RuntimeException (***是子类)来表示主叫做错了即传递一个 null 参数(然后抛出 NullPointerException )或非法参数(然后抛出 IllegalArgumentException ),或者方法在错误的时刻被调用/ state(然后抛出 IllegalStateException )等等。调用者应该修复他们的代码以避免这种情况。例如。如果参数不为null,或者参数是否为正确的格式/语法,或者确保在正确的时刻调用该方法,请事先检查。

Update: in general, you should only throw a RuntimeException (preferably one of its subclasses listed in the javadoc) to signal that the caller is doing it wrong. I.e. passing a null argument (then throw NullPointerException), or an illegal argument (then throw IllegalArgumentException), or the method is called 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.

如果有一个特定的情况,应该抛出一个运行时异常,你不能使用一个特定的子类,那么你应该扩展它,并在新的异常的javadoc和调用方法中正确地记录它,例如 ConfigurationException扩展了RuntimeException ,因为调用代码在使用前没有正确配置应用程序/ API。这应该足以证明最终用户(另一位开发人员)相应地采取行动。

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.

简而言之: RuntimeExceptions 应该以编程方式识别由故障引起的可恢复的问题代码流或配置(阅读:开发人员的故障)。已检查 例外情况 应该以编程方式识别出由于外部控制代码之外的意外状况(例如数据库关闭,文件I / O错误,错误的最终用户输入等)导致的可恢复的问题。 错误 应该以编程方式识别不可恢复的问题(例如,内存不足,初始化程序中的异常等)。

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