如何在java中为多个异常编写自定义异常?
我正在使用 smtp api,它会抛出 MessageException 和 IOException
但在我们的应用程序中,我们需要为两者提供包装异常。
是否可以为此编写包装异常?喜欢自定义异常?
I am using smtp api which throws MessageException and IOException
But in our application, we need to have wrapper exception for both.
Is it possible to write wrapper exception for this? like custom exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然。异常就是这样,并且可以包含任何东西;您不需要将它们编写为仅专门包装 IOException 或 MessageException。
上面是所有自定义异常的样子(在相关的情况下,它们可能还有更多字段来注册特定故障的特定信息,例如 SQLException 具有询问数据库“错误代码”的方法),但他们至少都具备上述条件。
然后,换行:
注意:传递给
MyException
的字符串应该很短,不应使用大写字母或感叹号,也不应在其末尾使用任何其他标点符号。此外,还应在其中包含实际的相关内容:例如,您尝试向其发送消息的用户(重点是,您在其中作为字符串常量包含的任何内容都必须简单、简短,并且不以标点符号结尾)。Sure. Exceptions just are, and can wrap anything; you don't need to write them as specifically wrapping only IOException or MessageExceptions.
The above is what all custom exceptions look like (where relevant they might have a few more fields that register specific info for a specific failure, e.g. SQLException has methods to ask for the DB 'error code'), but they all at least have the above.
Then, to wrap:
NB: The string you pass to your
MyException
should be short, should not use either caps or exclamation points, or for that matter any other punctuation at the end of it. In addition, include actual relevant content there too: For example, the user you tried to send a message for (the point is, whatever you include there as a string constant needs to be simple, short, and not end in punctuation).考虑创建一个根异常容器:
对于一些枚举或序列化要求,您也可以添加
exceptionCode
:然后从根 GeneralException 容器扩展您的
customException
:Consider to create a root Exception container as:
With some enumeration or serialization requirement you can add
exceptionCode
as well:Then extend your
customException
from root GeneralException container: