java.lang.Exception与滚动自己的异常 [英] java.lang.Exception vs. rolling your own exception

查看:169
本文介绍了java.lang.Exception与滚动自己的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在什么时候你将创建自己的异常类vs.使用java.lang.Exception? (所有时间?只有当它将在程序包外使用吗?只有当它必须包含高级逻辑等等)

解决方案

我认为你需要问自己一个完全不同的问题为我或使用我的代码的开发人员创造一个新的异常有什么优势?真正的唯一的优势,它给你或其他人是处理异常的能力。这似乎是一个明显的答案,但真的不是。您应该只处理可以合理恢复的异常。如果你抛出的异常是一个致命的错误,为什么会给开发者错误处理它?<​​/ p>

更深入的讨论:自定义例外:您应该何时创建它们?


At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)

解决方案

I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be handling exceptions that you can reasonably recover from. If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?

More in depth discussion: Custom exceptions: When should you create them?

这篇关于java.lang.Exception与滚动自己的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆