java HashMap返回NULL时如何处理异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13748113/
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
How to handle the exception when a HashMap returns NULL
提问by user1315906
I have a method as follows; It does some computation and then returns a HashMap.
我有一个方法如下;它进行一些计算,然后返回一个 HashMap。
public Map<Integer, Animal> method() {
// do some computation
returns hashMap;
}
1.) What hapence if the hash map returns null
, will i get an null pointer exception ? and if so should i handle it as
1.) 如果散列映射返回null
,我会得到空指针异常吗?如果是这样我应该处理它
public Map<Integer, Animal> method() throws{
So that the calling method will handle it ?
这样调用方法会处理它吗?
回答by José Roberto Araújo Júnior
When you get a object check if it is null... If a null value is not intended you can specify that it may throw a NullPointerException
just for documentation since it's a RunTimeException
and all RuntimeExceptions
can be trown anywhere.
当您得到一个对象时,检查它是否为空...如果不打算使用空值,您可以指定它可能会抛出一个NullPointerException
仅用于文档的对象,因为它是一个RunTimeException
并且所有内容RuntimeExceptions
都可以放在任何地方。
You can also do a:
您还可以执行以下操作:
try{
/* calculate */
}
catch(NullPointerException e){
/* process exception */
}
to process when a NullPointerException
happens, so you can revert the actions or close the resources or throw a more descriptive exception...
在NullPointerException
发生时进行处理,以便您可以恢复操作或关闭资源或抛出更具描述性的异常...
For example:
例如:
try{
Type o = (Type) map.get(key);
o.doSomething();
}
catch(NullPointerException e)
{
throw new RuntimeException("Null values are not accepted!", e);
}
回答by Addict
No, it will not give null pointer exception because you are just returning HashMap
. In calling method before doing any operation on returned HashMap
make sure to check that returned value is not null.
不,它不会给出空指针异常,因为您只是返回HashMap
. 在对HashMap
返回值进行任何操作之前调用方法,确保检查返回值不为空。
回答by Brian
A NullPointerException
occurs when you try to use the .
on a null
variable. For example:
NullPointerException
当您尝试.
在null
变量上使用 时会发生A。例如:
String s = null;
char c = s.charAt(0); // Tries to access null, throws NPE
Another place a NullPointerException
can occur is when you try to unbox a null
wrapper:
另一个NullPointerException
可能发生的地方是当您尝试拆箱null
包装时:
Integer integer = null;
int i = integer; // Tries to unbox null, throws NPE
These are the only ways you can ever get a NullPointerException
. Well, unless someone explicitly throws one:
这些是您获得NullPointerException
. 好吧,除非有人明确抛出一个:
throw new NullPointerException();
But you should neverdo that. Throw an IllegalArgumentException
instead.
但你永远不应该那样做。换一个IllegalArgumentException
。
That being said, returning null
from a method won't produce a NullPointerException
. However, using the .
on the result of that method when it doesreturn null
can:
话虽如此,null
从方法返回不会产生NullPointerException
. 然而,在使用.
上时,该方法的结果确实返回null
即可:
Map<Integer, Animal> map = method();
map.get(20); // Throws NPE if method() returns null
To fix this, you use a null
-check:
要解决此问题,请使用null
-check:
Map<Integer, Animal> map = method();
if (map != null)
map.get(20); // Never throws NPE
Note that we can still use map
as a reference, but we can't accessit since it's null
. That's the distinction it seems you're missing.
请注意,我们仍然可以将map
用作引用,但我们无法访问它,因为它是null
. 这就是您似乎缺少的区别。
Edit for your comment
编辑您的评论
So you are suggesting that I should leave
method()
as it is (without exception handling) and check it from the calling function?
所以你建议我应该保持
method()
原样(没有异常处理)并从调用函数中检查它?
That's one possible option. Another is throw an exception to indicate that it's null
if it's not supposed to be.
这是一种可能的选择。另一个是抛出异常以表明null
它是不应该的。
The big question is, is it allowedto be null
? If it is, then leave method()
as is, and check if it's null
when you call it like I have above. Indicate in your Javadoc comments that this method may return null
.
最大的问题是,是否允许为null
?如果是,则保持method()
原样,并检查是否null
像我上面那样称呼它。在您的 Javadoc 注释中指明此方法可能返回null
。
If it isn'tallowed to return null
, then when the method is called, either create the Map
or throw an exception. You can even create the map only when it's null
(this is called lazy initialization):
如果没有允许返回null
,那么当方法被调用,要么创建Map
或抛出异常。您甚至可以仅在映射时创建映射null
(这称为延迟初始化):
public Map<Integer, Animal> method() {
if (hashMap == null)
hashMap = new HashMap<Integer, Animal>();
return hashMap;
}
If your hashMap
is being created somewhere else, so this method shouldn't be called until after that other place created it (called a precondition), then you should throw an exception. For precondition violations, I usually use IllegalStateException
:
如果您hashMap
是在其他地方创建的,那么在其他地方创建它之前不应调用此方法(称为precondition),那么您应该抛出异常。对于前提条件违规,我通常使用IllegalStateException
:
public Map<Integer, Animal> method() {
if (hashMap == null)
throw new IllegalStateException("Must call otherMethod() to initialize hashMap before calling this method.");
return hashMap;
}