As a general rule, if the method should always return an object, then go with the exception. If you anticipate the occasional null and want to handle it in a certain way, go with the null.
Whatever you do, I highly advise against the third option: Returning a string that says "WTF".
if (TryFindObject(out object o)
// Do something with o
else
// o was not found
If null never indicates an error then just return null.
If null is always an error then throw an exception.
If null is sometimes an exception then code two routines. One routine throws an exception and the other is a boolean test routine that returns the object in an output parameter and the routine returns a false if the object was not found.
It's hard to misuse a Try routine. It's real easy to forget to check for null.
So when null is an error you just write
object o = FindObject();
When the null isn't an error you can code something like
if (TryFindObject(out object o)
// Do something with o
else
// o was not found
I just wanted to recapitulate the options mentioned before, throwing some new ones in:
return null
throw an Exception
use the null object pattern
provide a boolean parameter to you method, so the caller can chose if he wants you to throw an exception
provide an extra parameter, so the caller can set a value which he gets back if no value is found
Or you might combine these options:
Provide several overloaded versions of your getter, so the caller can decide which way to go. In most cases, only the first one has an implementation of the search algorithm, and the other ones just wrap around the first one:
Even if you choose to provide only one implementation, you might want to use a naming convention like that to clarify your contract, and it helps you should you ever decide to add other implementations as well.
You should not overuse it, but it may be helpfull, espeacially when writing a helper Class which you will use in hundreds of different applications with many different error handling conventions.
Cleaner control flow in your calling code. Checking for null injects a conditional branch which is natively handled by try/catch. Checking for null doesn't indicate what it is you're checking for - are you checking for null because you're looking for an error you're expecting, or are you checking for null so you don't pass it further on downchain?
Removes ambiguity of what "null" means. Is null representative of an error or is null what is actually stored in the value? Hard to say when you only have one thing to base that determination off of.
Improved consistency between method behavior in an application. Exceptions are typically exposed in method signatures, so you're more able to understand what edge cases the methods in an application account for, and what information your application can react to in a predictable manner.
Just ask yourself: "is it an exceptional case that the object is not found"? If it is expected to happen in the normal course of your program, you probably should not raise an exception (since it is not exceptional behavior).
Short version: use exceptions to handle exceptional behavior, not to handle normal flow of control in your program.
The interface of an objects is actually a contract between two objects, the caller must meet the contract or else the receiver may just fail with an exception. There are two possible contracts
1) all input the method is valid, in which case you must return null when the object is not found.
2) only some input is valid, ie that which results in a found object. In which case you MUST offer a second method that allows the caller to determine if its input will be correct. For example
is_present(key)
find(key) throws Exception
IF and ONLY IF you provide both methods of the 2nd contract, you are allowed to throw an exception is nothing is found!
I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.
Depends on what it means that the object is not found.
If it's a normal state of affairs, then return null. This is just something that might happen once in an while, and the callers should check for it.
If it's an error, then throw an exception, the callers should decide what to do with the error condition of missing object.
Ultimately either would work, although most people generally consider it good practice to only use Exceptions when something, well, Exceptional has happened.
If returning a collection, avoid returning null, return an empty collection which makes enumeration easier to deal with without a null check first.
Several .NET API's use the pattern of a thrownOnError parameter which gives the caller the choice as whether it is really an exceptional situation or not if the object is not found. Type.GetType is an example of this. Another common pattern with BCL is the TryGet pattern where a boolean is returned and the value is passed via an output parameter.
You could also consider the Null Object pattern in some circumstances which can either be a default or a version with no behaviour. The key is avoid null checks throughout the code base. See here for more information Link
True means throw, false means return some error return value. This way, whoever uses this function has both options. The default should be true, for the benefit of those who forget about error handling.
当找不到对象时,该方法返回 false。 与选项 A 相比,此方法的优点是您可以通过一个明确的步骤检查错误情况:
if (!findObject(myKey, myObj)) { ...
Return a null instead of throwing an exception and clearly document the possibility of a null return value in the API documentation. If the calling code doesn't honor the API and check for the null case, it will most probably result in some sort of "null pointer exception" anyway :)
In C++, I can think of 3 different flavors of setting up a method that finds an object.
Option A
Object *findObject(Key &key);
Return null when an object can't be found. Nice and simple. I'd go with this one. The alternative approaches below are for people who don't hate out-params.
Option B
void findObject(Key &key, Object &found);
Pass in a reference to variable that will be receiving the object. The method thrown an exception when an object can't be found. This convention is probably more suitable if it's not really expected for an object not to be found -- hence you throw an exception to signify that it's an unexpected case.
Option C
bool findObject(Key &key, Object &found);
The method returns false when an object can't be found. The advantage of this over option A is that you can check for the error case in one clear step:
referring only to the case where null is not considered an exceptional behavior i am definitely for the try method, it is clear, no need to "read the book" or "look before you leap" as was said here
so basically:
bool TryFindObject(RequestParam request, out ResponseParam response)
and this means that the user's code will also be clear
If it's important for client code to know the difference between found and not found and this is supposed to be a routine behavior, then it's best to return null. Client code can then decide what to do.
Unfortunately JDK is inconsistent, if you trying access non existing key in resource bundle, you get not found exception and when you request value from map you get null if it doesn't exists. So I would change winner answer to the following, if found value can be null, then raise exception when it isn't found, otherwise return null. So follow to the rule with one exception, if you need to know why value isn't found then always raise exception, or..
If the method returns a collection, then return an empty collection (like sayed above). But please not Collections.EMPTY_LIST or such! (in case of Java)
If the method retrives a single object, then You have some options.
If the method should always find the result and it's a real exception case not to find the object, then you should throw an exception (in Java: please an unchecked Exception)
(Java only) If you can tolerate that the method throws a checked exception, throw a project specific ObjectNotFoundException or the like. In this case the compiler says you if you forget to handle the exception. (This is my preferred handling of not found things in Java.)
If you say it's really ok, if the object is not found and your Method name is like findBookForAuthorOrReturnNull(..), then you can return null. In this case it is strongly recomminded to use some sort of static check or compiler check, wich prevents dereferencing of the result without a null check. In case of Java it can be eg. FindBugs (see DefaultAnnotation at http://findbugs.sourceforge.net/manual/annotations.html) or IntelliJ-Checking.
Be careful, if you decide to return a null. If you are not the only programmer in project you will get NullPointerExceptions (in Java or whatever in other Languages) at run time! So don't return nulls which are not checked at compile time.
然而,如果它返回整个该死的东西(就像在 C++ 中,如果你这样做:“return blah;”而不是“return &blah;”(或者“blah”是一个指针),那么你就不能返回 NULL,因为它不是“对象”类型,在这种情况下,抛出异常或返回没有设置成功标志的空白对象是我解决问题的方法。
As long as it's supposed to return a reference to the object, returning a NULL should be good.
However, if it's returning the whole bloody thing (like in C++ if you do: 'return blah;' rather than 'return &blah;' (or 'blah' is a pointer), then you can't return a NULL, because it's not of type 'object'. In that case, throwing an exception, or returning a blank object that doesn't have a success flag set is how I would approach the problem.
Don't think anyone mentioned the overhead in exception handling - takes additional resources to load up and process the exception so unless its a true app killing or process stopping event (going forward would cause more harm than good) I would opt for passing back a value the calling environment could interpret as it sees fit.
I agree with what seems to be the consensus here (return null if "not found" is a normal possible outcome, or throw an exception if the semantics of the situation require that the object always be found).
There is, however, a third possibility that might make sense depending on your particular situation. Your method could return a default object of some sort in the "not found" condition, allowing calling code to be assured that it will always receive a valid object without the need for null checking or exception catching.
public class Main {
public static void main(String[] args) {
Example example = new Example();
try {
Example2 obj = example.doExample();
if(obj == null){
System.out.println("Hey object is null!");
}
} catch (Exception e) {
System.out.println("Congratulations, you caught the exception!");
System.out.println("Here is stack trace:");
e.printStackTrace();
}
}
}
Example.java
/**
* Example.java
* @author Seval
* @date 10/22/2014
*/
public class Example {
/**
* Returns Example2 object
* If there is no Example2 object, throws exception
*
* @return obj Example2
* @throws Exception
*/
public Example2 doExample() throws Exception {
try {
// Get the object
Example2 obj = new Example2();
return obj;
} catch (Exception e) {
// Log the exception and rethrow
// Log.logException(e);
throw e;
}
}
}
Example2.java
/**
* Example2.java
* @author Seval
*
*/
public class Example2 {
/**
* Constructor of Example2
* @throws Exception
*/
public Example2() throws Exception{
throw new Exception("Please set the \"obj\"");
}
}
If you are using a library or another class which throws an exception, you should rethrow it. Here is an example. Example2.java is like library and Example.java uses it's object. Main.java is an example to handle this Exception. You should show a meaningful message and (if needed) stack trace to the user in the calling side.
Main.java
public class Main {
public static void main(String[] args) {
Example example = new Example();
try {
Example2 obj = example.doExample();
if(obj == null){
System.out.println("Hey object is null!");
}
} catch (Exception e) {
System.out.println("Congratulations, you caught the exception!");
System.out.println("Here is stack trace:");
e.printStackTrace();
}
}
}
Example.java
/**
* Example.java
* @author Seval
* @date 10/22/2014
*/
public class Example {
/**
* Returns Example2 object
* If there is no Example2 object, throws exception
*
* @return obj Example2
* @throws Exception
*/
public Example2 doExample() throws Exception {
try {
// Get the object
Example2 obj = new Example2();
return obj;
} catch (Exception e) {
// Log the exception and rethrow
// Log.logException(e);
throw e;
}
}
}
Example2.java
/**
* Example2.java
* @author Seval
*
*/
public class Example2 {
/**
* Constructor of Example2
* @throws Exception
*/
public Example2() throws Exception{
throw new Exception("Please set the \"obj\"");
}
}
That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:
发布评论
评论(30)
如果您总是期望找到一个值,那么如果该值丢失则抛出异常。 出现异常就意味着存在问题。
如果该值可能缺失或存在,并且两者对于应用程序逻辑都有效,则返回 null。
更重要的是:你在代码的其他地方做了什么? 一致性很重要。
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do other places in the code? Consistency is important.
仅当确实是错误时才抛出异常。 如果对象的预期行为不存在,则返回 null。
否则,这是一个偏好问题。
Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null.
Otherwise it is a matter of preference.
作为一般规则,如果方法应该始终返回一个对象,那么就处理异常。 如果您预计偶尔会出现空值并希望以某种方式处理它,请使用空值。
无论你做什么,我强烈建议不要使用第三种选择:返回一个显示“WTF”的字符串。
As a general rule, if the method should always return an object, then go with the exception. If you anticipate the occasional null and want to handle it in a certain way, go with the null.
Whatever you do, I highly advise against the third option: Returning a string that says "WTF".
如果 null 从未指示错误,则仅返回 null。
如果 null 始终是错误,则抛出异常。
如果 null 有时是一个异常,则编写两个例程。 一个例程引发异常,另一个例程是布尔测试例程,它在输出参数中返回对象,如果未找到该对象,则该例程返回 false。
很难滥用 Try 例程。 很容易忘记检查是否为空。
因此,当 null 是一个错误时,您只需编写
当 null 不是一个错误时,您可以编写类似的代码
If null never indicates an error then just return null.
If null is always an error then throw an exception.
If null is sometimes an exception then code two routines. One routine throws an exception and the other is a boolean test routine that returns the object in an output parameter and the routine returns a false if the object was not found.
It's hard to misuse a Try routine. It's real easy to forget to check for null.
So when null is an error you just write
When the null isn't an error you can code something like
我只是想概括一下前面提到的选项,在其中添加一些新选项:
或者您可以组合这些选项:
提供 getter 的多个重载版本,以便调用者可以决定走哪条路。 在大多数情况下,只有第一个具有搜索算法的实现,而其他算法只是围绕第一个实现:
即使您选择仅提供一个实现,您也可能希望使用这样的命名约定来阐明您的合同,如果您决定添加其他实现,它也会对您有所帮助。
您不应该过度使用它,但它可能会有所帮助,特别是在编写辅助类时,您将在数百个具有许多不同错误处理约定的不同应用程序中使用该辅助类。
I just wanted to recapitulate the options mentioned before, throwing some new ones in:
Or you might combine these options:
Provide several overloaded versions of your getter, so the caller can decide which way to go. In most cases, only the first one has an implementation of the search algorithm, and the other ones just wrap around the first one:
Even if you choose to provide only one implementation, you might want to use a naming convention like that to clarify your contract, and it helps you should you ever decide to add other implementations as well.
You should not overuse it, but it may be helpfull, espeacially when writing a helper Class which you will use in hundreds of different applications with many different error handling conventions.
使用空对象模式或引发异常。
Use the null object pattern or throw an exception.
抛出异常的优点:
有关示例的更多说明,请参阅:http:// metatations.com/2011/11/17/returning-null-vs-throwing-an-exception/
Advantages of throwing an exception:
For more explanation with examples, see: http://metatations.com/2011/11/17/returning-null-vs-throwing-an-exception/
这取决于您的语言和代码是否促进:
LBYL(三思而后行)
或者
EAFP(请求宽恕比请求许可更容易)
LBYL 表示您应该检查值(因此返回 null)
EAFP 说尝试操作并查看它是否失败(抛出异常),
尽管我同意上面的观点。异常应该用于异常/错误条件,并且在使用检查时返回 null 是最好的。
Python 中的 EAFP 与 LBYL:
http://mail.python.org/pipermail/python-list /2003年5月/205182.html
(网络档案)
it depends if your language and code promotes:
LBYL (look before you leap)
or
EAFP (easier to ask forgiveness than permission)
LBYL says you should check for values (so return a null)
EAFP says to just try the operation and see if it fails (throw an exception)
though I agree with above.. exceptions should be used for exceptional/error conditions, and returning a null is best when using checks.
EAFP vs. LBYL in Python:
http://mail.python.org/pipermail/python-list/2003-May/205182.html
(Web Archive)
与您正在使用的 API 保持一致。
Be consistent with the API(s) you're using.
只要问问自己:“没有找到该对象是否属于例外情况”? 如果预计它会在程序的正常过程中发生,您可能不应该引发异常(因为这不是异常行为)。
简短版本:使用异常来处理异常行为,而不是处理程序中的正常控制流。
-艾伦。
Just ask yourself: "is it an exceptional case that the object is not found"? If it is expected to happen in the normal course of your program, you probably should not raise an exception (since it is not exceptional behavior).
Short version: use exceptions to handle exceptional behavior, not to handle normal flow of control in your program.
-Alan.
例外情况与合同设计有关。
对象的接口实际上是两个对象之间的契约,调用者必须满足契约,否则接收者可能会因异常而失败。 有两种可能的约定
1)所有输入方法都有效,在这种情况下,当未找到对象时必须返回 null。
2) 只有一些输入是有效的,即导致找到对象的输入。 在这种情况下,您必须提供第二种方法,允许调用者确定其输入是否正确。 例如
,如果并且仅如果您提供第二个合约的两种方法,则允许您在未找到任何内容的情况下抛出异常!
Exceptions are related to Design by Contract.
The interface of an objects is actually a contract between two objects, the caller must meet the contract or else the receiver may just fail with an exception. There are two possible contracts
1) all input the method is valid, in which case you must return null when the object is not found.
2) only some input is valid, ie that which results in a found object. In which case you MUST offer a second method that allows the caller to determine if its input will be correct. For example
IF and ONLY IF you provide both methods of the 2nd contract, you are allowed to throw an exception is nothing is found!
我更喜欢只返回 null,并依赖调用者来适当地处理它。 (由于缺乏更好的词)例外是如果我绝对“确定”此方法将返回一个对象。 在这种情况下,失败是一个例外,应该并且应该抛出。
I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.
取决于未找到该对象意味着什么。
如果是正常情况,则返回 null。 这只是偶尔发生的事情,调用者应该检查一下。
如果是错误,则抛出异常,调用者应该决定如何处理丢失对象的错误情况。
最终,两者都可以工作,尽管大多数人通常认为仅在发生异常情况时才使用异常是一种很好的做法。
Depends on what it means that the object is not found.
If it's a normal state of affairs, then return null. This is just something that might happen once in an while, and the callers should check for it.
If it's an error, then throw an exception, the callers should decide what to do with the error condition of missing object.
Ultimately either would work, although most people generally consider it good practice to only use Exceptions when something, well, Exceptional has happened.
这里还有一些建议。
如果返回一个集合,请避免返回 null,返回一个空集合,这使得枚举更容易处理,而无需先进行 null 检查。
一些 .NET API 使用 throwOnError 参数的模式,该模式使调用者可以选择在未找到对象时是否确实是异常情况。 Type.GetType 就是一个例子。 BCL 的另一个常见模式是 TryGet 模式,其中返回布尔值并通过输出参数传递值。
在某些情况下,您还可以考虑空对象模式,它可以是默认模式,也可以是没有行为的版本。 关键是在整个代码库中避免空检查。 请参阅此处了解更多信息 链接
Here are a couple more suggestions.
If returning a collection, avoid returning null, return an empty collection which makes enumeration easier to deal with without a null check first.
Several .NET API's use the pattern of a thrownOnError parameter which gives the caller the choice as whether it is really an exceptional situation or not if the object is not found. Type.GetType is an example of this. Another common pattern with BCL is the TryGet pattern where a boolean is returned and the value is passed via an output parameter.
You could also consider the Null Object pattern in some circumstances which can either be a default or a version with no behaviour. The key is avoid null checks throughout the code base. See here for more information Link
在某些函数中我添加了一个参数:
True表示抛出,False表示返回一些错误返回值。 这样,无论谁使用这个功能,都有两种选择。 默认值应该是 true,这对于那些忘记错误处理的人来说是有利的。
In some functions I add a parameter:
True means throw, false means return some error return value. This way, whoever uses this function has both options. The default should be true, for the benefit of those who forget about error handling.
返回 null 而不是抛出异常,并在 API 文档中清楚地记录 null 返回值的可能性。 如果调用代码不遵守 API 并检查 null 情况,那么它很可能会导致某种“空指针异常”:)
在 C++ 中,我可以想到 3 种不同风格的设置方法:找到一个物体。
选项 A
当找不到对象时返回 null。 又好又简单。 我会选择这个。 下面的替代方法适合那些不讨厌外参数的人。
选项 B
传递对将接收对象的变量的引用。 当找不到对象时,该方法会引发异常。 如果确实不希望找不到对象,则此约定可能更合适 - 因此您抛出异常来表示这是意外情况。
选项 C
当找不到对象时,该方法返回 false。 与选项 A 相比,此方法的优点是您可以通过一个明确的步骤检查错误情况:
Return a null instead of throwing an exception and clearly document the possibility of a null return value in the API documentation. If the calling code doesn't honor the API and check for the null case, it will most probably result in some sort of "null pointer exception" anyway :)
In C++, I can think of 3 different flavors of setting up a method that finds an object.
Option A
Return null when an object can't be found. Nice and simple. I'd go with this one. The alternative approaches below are for people who don't hate out-params.
Option B
Pass in a reference to variable that will be receiving the object. The method thrown an exception when an object can't be found. This convention is probably more suitable if it's not really expected for an object not to be found -- hence you throw an exception to signify that it's an unexpected case.
Option C
The method returns false when an object can't be found. The advantage of this over option A is that you can check for the error case in one clear step:
仅指 null 不被视为异常行为的情况,我绝对支持 try 方法,很明显,不需要像这里所说的那样“阅读书籍”或“三思而后行”
:
这意味着用户的代码也将是清晰的
referring only to the case where null is not considered an exceptional behavior i am definitely for the try method, it is clear, no need to "read the book" or "look before you leap" as was said here
so basically:
and this means that the user's code will also be clear
如果客户端代码了解已找到和未找到之间的区别很重要,并且这应该是常规行为,那么最好返回 null。 然后客户端代码可以决定要做什么。
If it's important for client code to know the difference between found and not found and this is supposed to be a routine behavior, then it's best to return null. Client code can then decide what to do.
一般情况下应该返回null。 调用该方法的代码应该决定是抛出异常还是尝试其他操作。
Generally it should return null. The code calling the method should decide whether to throw an exception or to attempt something else.
或者返回一个选项
选项基本上是一个容器类,强制客户端处理展位案例。 Scala有这个概念,查一下它的API。
然后,您可以在该对象上使用类似 T getOrElse(T valueIfNull) 的方法,它们要么返回找到的对象,要么返回客户端指定的替代对象。
Or return an Option
An option is basically a container class that forces the client to handle booth cases. Scala has this concept, look up it's API.
Then you have methods like T getOrElse(T valueIfNull) on this object thet either return the found object, or an allternative the client specifieces.
更喜欢返回 null ——
如果调用者在没有检查的情况下使用它,无论如何都会发生异常。
如果调用者并不真正使用它,请不要向他征收
try
/catch
块Prefer returning null --
If the caller uses it without checking, the exception happens right there anyway.
If the caller doesn't really use it, don't tax him a
try
/catch
block不幸的是,JDK 是不一致的,如果您尝试访问资源包中不存在的密钥,则会出现未找到异常,并且当您从映射请求值时,如果不存在,则会得到 null。 因此,我会将获胜者答案更改为以下内容,如果找到的值可以为 null,则在未找到时引发异常,否则返回 null。 因此,请遵循有一个例外的规则,如果您需要知道为什么找不到值,那么总是引发异常,或者..
Unfortunately JDK is inconsistent, if you trying access non existing key in resource bundle, you get not found exception and when you request value from map you get null if it doesn't exists. So I would change winner answer to the following, if found value can be null, then raise exception when it isn't found, otherwise return null. So follow to the rule with one exception, if you need to know why value isn't found then always raise exception, or..
如果该方法返回一个集合,则返回一个空集合(如上所述)。 但请不要 Collections.EMPTY_LIST 之类的! (对于 Java)
如果该方法检索单个对象,那么您有一些选择。
如果您决定返回 null,请小心。 如果您不是项目中唯一的程序员,您将在运行时得到 NullPointerExceptions(在 Java 或其他语言中)! 因此,不要返回编译时未检查的空值。
If the method returns a collection, then return an empty collection (like sayed above). But please not Collections.EMPTY_LIST or such! (in case of Java)
If the method retrives a single object, then You have some options.
Be careful, if you decide to return a null. If you are not the only programmer in project you will get NullPointerExceptions (in Java or whatever in other Languages) at run time! So don't return nulls which are not checked at compile time.
只要它应该返回对象的引用,返回 NULL 应该是好的。
然而,如果它返回整个该死的东西(就像在 C++ 中,如果你这样做:“return blah;”而不是“return &blah;”(或者“blah”是一个指针),那么你就不能返回 NULL,因为它不是“对象”类型,在这种情况下,抛出异常或返回没有设置成功标志的空白对象是我解决问题的方法。
As long as it's supposed to return a reference to the object, returning a NULL should be good.
However, if it's returning the whole bloody thing (like in C++ if you do: 'return blah;' rather than 'return &blah;' (or 'blah' is a pointer), then you can't return a NULL, because it's not of type 'object'. In that case, throwing an exception, or returning a blank object that doesn't have a success flag set is how I would approach the problem.
不要以为有人提到了异常处理的开销 - 需要额外的资源来加载和处理异常,因此除非它是真正的应用程序终止或进程停止事件(继续下去会造成弊大于利),否则我会选择传回调用环境可以按其认为合适的方式解释的值。
Don't think anyone mentioned the overhead in exception handling - takes additional resources to load up and process the exception so unless its a true app killing or process stopping event (going forward would cause more harm than good) I would opt for passing back a value the calling environment could interpret as it sees fit.
我同意这里似乎达成的共识(如果“未找到”是正常的可能结果,则返回 null,或者如果情况的语义要求始终找到对象,则抛出异常)。
然而,根据您的具体情况,还有第三种可能性可能有意义。 您的方法可以在“未找到”条件下返回某种默认对象,从而确保调用代码始终会收到有效的对象,而无需进行 null 检查或异常捕获。
I agree with what seems to be the consensus here (return null if "not found" is a normal possible outcome, or throw an exception if the semantics of the situation require that the object always be found).
There is, however, a third possibility that might make sense depending on your particular situation. Your method could return a default object of some sort in the "not found" condition, allowing calling code to be assured that it will always receive a valid object without the need for null checking or exception catching.
返回 null,异常就是:您的代码执行了预期之外的操作。
Return a null, exceptions are exactly that: something your code does that isn't expected.
例外应该是例外。 如果返回 null 有效,则返回 null。
Exceptions should be exceptional. Return null if it is valid to return a null.
如果您使用的库或其他类抛出异常,您应该重新抛出它。 这是一个例子。 Example2.java 就像库,Example.java 使用它的对象。 Main.java 是处理此异常的示例。 您应该向调用方的用户显示有意义的消息和(如果需要)堆栈跟踪。
Main.java
Example.java
Example2.java
If you are using a library or another class which throws an exception, you should rethrow it. Here is an example. Example2.java is like library and Example.java uses it's object. Main.java is an example to handle this Exception. You should show a meaningful message and (if needed) stack trace to the user in the calling side.
Main.java
Example.java
Example2.java
这实际上取决于您是否希望找到该物体。 如果您遵循异常应该用于指示某事的思想流派,那么,错误,发生了异常,那么:
,否则返回 null。
That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:
Otherwise, return null.