java.lang.Exception 与滚动您自己的异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/237585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.Exception vs. rolling your own exception
提问by mcjabberz
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...)
与使用 java.lang.Exception 相比,您会在什么时候创建自己的异常类?(一直以来?仅当它在包外使用时?仅当它必须包含高级逻辑时?等等...)
采纳答案by JaredPar
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?
更深入的讨论:自定义异常:您应该何时创建它们?
回答by alex
Reason one:
原因一:
Need to catch specific stuff. If calling code needs to deal with a specific exceptional condition, you need to differentiate your Exception, and Java differentiates exceptions with different types, so you need to write your own.
需要捕捉特定的东西。如果调用代码需要处理特定的异常情况,就需要区分你的Exception,Java区分不同类型的异常,所以需要自己写。
Basically, if someone has to write:
基本上,如果有人必须写:
catch(ExistingException e) {
if({condition}) {
{ some stuff here}
}
else {
{ different stuff here}
}
}
You probably want to write a specific extension; catch Exception matching is clearer than conditionals, IMHO.
你可能想写一个特定的扩展;catch 异常匹配比条件更清晰,恕我直言。
Remember: your new Exception can bea subclass of RuntimeException
请记住:您的新 Exception可以是RuntimeException 的子类
Reason two:
原因二:
API consolidation. If you write an interface and you have several implementations, it's possible that they will call different APIs with a whole bunch of different non-RuntimeExceptions thrown:
API 整合。如果您编写一个接口并且有多个实现,则它们可能会调用不同的 API,并抛出一大堆不同的非运行时异常:
interface MyInterface {
void methodA();
}
class MyImplA {
void methodA() throws SQLException { ... }
}
class MyImplB {
void methodA() throws IOException { ... }
}
Do you really want MyInterface.methodA to throw SQLException and IOException? Maybe then it makes sense to wrap the possible exceptions in a custom Exception. Which again can be a RuntimeException. Or even RuntimeException itself...
你真的想让 MyInterface.methodA 抛出 SQLException 和 IOException 吗?也许然后将可能的异常包装在自定义异常中是有意义的。这又可以是一个 RuntimeException。甚至 RuntimeException 本身...
回答by slim
I believe that:
我相信:
catch (Exception e) {
...
}
... is an antipattern that should be avoided. You might want one centralized broad catch somewhere in your application, to log an error and prevent the whole application from terminating - but having them scattered around willy-nilly is bad.
... 是一种应该避免的反模式。您可能希望在应用程序的某处有一个集中的广泛捕获,以记录错误并防止整个应用程序终止 - 但将它们随意分散是不好的。
Why:
为什么:
try {
if(myShape.isHidden()) {
throw new Exception();
}
// More logic
} catch (Exception e) {
MyApp.notify("Can't munge a hidden shape");
}
So you try this, and due to a coding error, myShape is null. A NullPointerException gets thrown when the runtime tries to derefence myShape. This code reports a hidden shape, when it should be reporting a null pointer.
所以你试试这个,由于编码错误,myShape 为空。当运行时尝试取消对 myShape 的引用时,会抛出 NullPointerException。这段代码报告了一个隐藏的形状,而它应该报告一个空指针。
Either make your own exception, or find a suitably specialized exception in the API. It's not as if extending Exception or RuntimeException is onerous.
要么创建自己的异常,要么在 API 中找到合适的专门异常。扩展 Exception 或 RuntimeException 并不麻烦。
回答by Andru Luvisi
When I want to treat my exceptions differently from everybody else's. If I want to catch mine and propagate everyone else's, or if I want to catch someone else's and propagate mine, or if I want to catch both but treat them differently, then I will define a separate class for my exceptions. If I want to treat them all the same, either by propagating both or by catching both (and doing the same thing either way with the caught exceptions), the I will use the standard class.
当我想以不同于其他人的方式对待我的例外时。如果我想捕捉我的并传播其他人的,或者如果我想捕捉其他人的并传播我的,或者如果我想捕捉两者但区别对待它们,那么我将为我的异常定义一个单独的类。如果我想对它们一视同仁,要么通过传播两者,要么通过捕获两者(并对捕获的异常做同样的事情),我将使用标准类。
回答by anjanb
IF there is an existing Exception with the language runtime or libraries, use it ELSE create your own, document it well and that should work in 99% of the cases.
如果语言运行时或库存在现有异常,请使用它 否则创建您自己的异常,并对其进行良好记录,这应该适用于 99% 的情况。
回答by S.Lott
Software captures meaning.
软件捕捉意义。
There are almost no reasons for throwing an existing exception: the JVM already does that for you. Your version of their exception isn't really accurate and throwing "Exception" isn't meaningful, either.
几乎没有理由抛出现有的异常:JVM 已经为您做到了。你的异常版本并不准确,抛出“异常”也没有意义。
You might have a DataFormatExceptionbecause of a parsing algorithm you wrote. This, however, is rare.
DataFormatException由于您编写的解析算法,您可能有一个。然而,这种情况很少见。
When your program encounters an exceptional situation, it's almost always unique to your program. Why force-fit your exceptional situation into an existing exception? If it's unique to your program, then... well... it's unique. Name it that way.
当您的程序遇到异常情况时,它几乎总是您的程序所独有的。为什么要将您的异常情况强加到现有的异常中?如果它对您的程序来说是独一无二的,那么......好吧......它是独一无二的。这样命名。
Do not, however, provide a unique exception class for each unique message. One exception classcan have many variant messages and supporting details.
但是,不要为每个唯一的消息提供唯一的异常类。一个异常类可以有许多变体消息和支持细节。
The Python rule of thumb, translated to Java, is to define any unique exceptions at the package level. [In Python, they suggest exceptions at the "module" level, something that doesn't precisely translate to Java.]
转换为 Java 的 Python 经验法则是在包级别定义任何独特的异常。[在 Python 中,他们建议在“模块”级别出现异常,这并不能准确地转换为 Java。]
回答by iny
Start always by using the common exception classes and then when a need appears to handle it specially, change it.
总是从使用公共异常类开始,然后当需要特别处理它时,更改它。
When creating a method first time, just let exceptions go through.
If there are exceptions that must be handled, those can either be just defined in throws or wrapped to some runtime exception or wrapped own throws exception. I prefer runtime exceptions in many cases. Defining throws definition should be avoided until there is a need for it from API point of view.
Later when a need appears to do specific handling for an exception in some caller, come back and create new exception for it.
第一次创建方法时,只需让异常通过。
如果存在必须处理的异常,则这些异常可以仅在 throws 中定义或包装到某个运行时异常或包装自己的 throws 异常。在许多情况下,我更喜欢运行时异常。在从 API 的角度来看需要它之前,应该避免定义 throws 定义。
稍后,当需要对某个调用者中的异常进行特定处理时,请返回并为其创建新的异常。
The point is to avoid doing extra work before knowing what is needed.
关键是在知道需要什么之前避免做额外的工作。
回答by matt b
I can't imagine specifically throwing a java.lang.Exception if some object/class/method had a problem. It's too generic - if you're not going to create your own Exception class, seems to me like there ought to at least be a more specific Exception-type in the API.
如果某个对象/类/方法有问题,我无法想象特别抛出 java.lang.Exception 。它太通用了 - 如果您不打算创建自己的 Exception 类,在我看来,API 中至少应该有一个更具体的 Exception 类型。
回答by Vincent Ramdhanie
I would use the exceptions from the Java API when the exception relates to the API. But if an exceptional situation arises that is unique to my own API then I will create an Exception for it. For example if I have a Range object with two properties min and max and the invariant min <= max then I will create an exception InvalidRangeException.
当异常与 API 相关时,我会使用来自 Java API 的异常。但是,如果出现我自己的 API 独有的异常情况,那么我将为它创建一个异常。例如,如果我有一个具有两个属性 min 和 max 以及不变 min <= max 的 Range 对象,那么我将创建一个异常 InvalidRangeException。
When I am writing code this helps because I know if the exception originates because I violated one of my own conditions or its something from the Java API.
当我编写代码时,这会有所帮助,因为我知道异常是否源于我自己的条件之一或来自 Java API 的某些条件。
回答by Rahul
In most cases it doesn't make sense to create your own exception class.
在大多数情况下,创建自己的异常类是没有意义的。
There is a tendency in novice programmers to create their own exception class just so they can use a name that is more indicative of the type of error. So you'll find classes like FTPInitializationException, DAOFactoryException etc. even though such exceptions are not being handled differently than standard exceptions. This is clearly an anti pattern that should be avoided.
新手程序员倾向于创建自己的异常类,以便他们可以使用更能指示错误类型的名称。因此,您会发现诸如 FTPInitializationException、DAOFactoryException 等类,即使这些异常的处理方式与标准异常没有区别。这显然是一种应该避免的反模式。

