您在Java中如何以及在何处定义自己的Exception层次结构? [英] How and where do you define your own Exception hierarchy in Java?

查看:104
本文介绍了您在Java中如何以及在何处定义自己的Exception层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中如何以及在何处定义自己的Exception层次结构?

How and where do you define your own Exception hierarchy in Java?

我的主要问题涉及必须定义异常类的包位置。

My main question concerns package location where your Exception classes must be defined.

我们是否为异常创建了一个特殊包并将所有类放在其中?

Do we create a special package for our exceptions and put all classes inside it?

推荐答案

我将此作为一般规则使用。

I use this as a general rule.


  • 如果有意义,请使用预定义的Java异常。例如,如果您的代码有某种I / O错误,则可以抛出IOException。

  • 如果您需要在try中区分这两个异常,则仅使用异常层次结构/ catch块。很多时候,让一个组件抛出一个异常类型,并针对不同的错误使用不同的消息,这是很好的。如果用户无法真正做任何事情来专门处理错误,请使用相同的通用异常类。如果用户能够以不同方式处理它们,那就是应该使用层次结构。

  • 对于层次结构,不要使来自不同组件的所有异常都从基本异常继承。没有真正的理由这样做。如果消费者希望捕获任何内容,他们可以简单地捕获异常。

  • 对于包位置,我将Exception类与其相关的代码放在一起。因此,如果我在a.b.c包中有一个BusinessService,那么我有一个a.b.c.BusinessException。我并不喜欢将所有异常放入异常包中。它只是很难找到。

  • Where it makes sense, use a pre-defined Java exception. For example, if your code has some sort of I/O Error, it is fine to throw an IOException.
  • Only use exception hierarchies if you need to differentiate between the two exceptions in a try/catch block. A lot of times it is perfectly fine to have a single component throw a single exception type with different messages for different errors. If the user cannot really do anything to handle the error specially, use the same generic exception class. If the user is able to handle them differently, that is when you should use a hierarchy.
  • For hierarchies, do not make all exceptions from different components inherit from a base exception. There is no real reason to do this. If the consumer wants to catch anything, they can simply catch Exception.
  • For package location, I put an Exception class with the code it relates to. So if I have a BusinessService in a package a.b.c, I have a a.b.c.BusinessException to go with it. I'm not a fan of putting all exceptions into an exceptions package. It just makes it hard to find.

这篇关于您在Java中如何以及在何处定义自己的Exception层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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