Good practices for Java exceptions handling [closed]

ⅰ亾dé卋堺 提交于 2019-11-30 20:23:40

It looks like your tech-lead, as often, has escaped his role of developer because he wasn't good at it.

My advices would be:

  • prefer runtime exceptions over checked exceptions, especially if you're not the only client of your API. Using a checked exception forces every client to handle the exception, even if it can't do anything about it. If this is really what you want to do (i.e. forcing the caller to handle it), then a checked exception is what you want.
  • if the only thing the client can do when an exception happens is displaying a more or less generic error message such as "oops, something bad happened, please retry or go back to the welcome page", then definitely use runtime exceptions. Most of the presentation frameworks provide a way to use a generic error handler.
  • definitely use exceptions that are linked to your abstraction layer. Throwing a SQLException from a high-level service is not adequate. Use existing exception types when they're appropriate (like IllegalArgumentException to signal an illegal argument). Otherwise, wrap the low-level exception into a higher-level, appropriate exception type. What is costly is to throw an exception. Whether it wraps another one or not doesn't matter much. And it should only happen exceptionally anyway.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!