Is there a sense to handle null pointer exception by such way like
private void doWork(Object object) {
if (object == null) {
try {
throw new IllegalArgumentException();
} catch (Exception e) {
e.printStackTrace();
}
} else {
...
}
}
No, that doesn't really make sense.
Don't catch the exception. Just do
if (object == null)
throw new IllegalArgumentException("Argument object may not equal null");
According to your suggestion the method would be document as
Do some work given argument object. If object is null it prints some garbage on standard out and does nothing else.
As a side-note, since you're still learning Java, your try-catch block:
try {
throw new IllegalArgumentException();
} catch (Exception e) {
e.printStackTrace();
}
... is equivalent to ...
new IllegalArgumentException().printStackTrace();
It's fine to throw an exception if a null is an exceptional state, but the try/catch does not make much sense: you throw a new IllegalArgumentException();, catch it right afterwards, print a stacktrace an continue.
If you can handle the null case and just want to report, then you should write it to a log file:
if (object == null) {
log.warn("method doWork has been called with a null argument");
}
// continue in the method
Otherwise the method should throw the exception back at it's caller
if (object == null) {
throw new IllegalArgumentException("Hey stupid, RTFJD, NO calls with null!");
}
(replace exception message with something meaningful ;) )
First, that code could be written more simply as:
private void doWork(Object object) {
if (object == null) {
new IllegalArgumentException().printStackTrace();
} else {
}
}
or (almost equivalently) as
private void doWork(Object object) {
if (object == null) {
Thread.dumpStack();
} else {
}
}
Second, is it doing something useful? Yes, it is printing is a stack trace for the current thread.
Third, is it a good idea? IMO, definitely NOT.
It is sending stuff to the standard error, which may be going to the console (where it could be lost if nobody is watching) or to /dev/null. Errors should be logged properly using your preferred logging subsystem.
It looks like it is squashing a probable error condition (i.e. the program is broken because this method has been called with an illegal argument) and then continuing. If this is really an error condition, then the code should probably be bailing out. If it is not, then the stack trace is noise.
In short, this looks like a "bandaid" solution to some problem. The correct solution is to remove this code (or replace it with code that simply throws IllegalArgumentException), and when the exception occurs figure out where it is coming from and fix the root problem.
Alternative:
private void throwIfNull(Object object, String message) throws NullPointerException {
if (object == null) {
throw new NullPointerException(message);
}
}
Then you can specify your method to throw the exception back to the caller, like so
private void doWork(Object object) throws Exception {
throwIfNull(object, "Object is null");
//Other work....
doWorkInternal(object);
}
In this case, you know that if doWorkInternal() method is called, the object was never null.
The simplest way is
if (object != null) {
doWork();
} else {
}
if you don't want to catch the exception inside your function and let some calling function to handle this,
its better to do this :
public void doWork(Object object) throws NullPointerException {
//code that might result NullPointerException.
//no handling of exception by yourself
}
But if want/should handle the exception within the definition of your method,
your code is good.
When object came as null, it will automatically throw an null pointer exception. but you didn't handle it, and you are trying to throw an "IllegalArgumentException()", which isn't possible.
if (object == null)
this line itself, an exception is thrown, and it won't execute the rest of the line.
Related
Recently I saw following piece of code on GitHub:
private static String safeToString(Object obj) {
if (obj == null) return null;
try {
return obj.toString();
} catch (Throwable t) {
return "Error occured";
}
}
I've never placed toString() method invocations inside the try-catch blocks. But now when I think about it, it might make sense. For example someone could overwrite toString() method in it's class that might throw a runtime exception, like NullPointerException. So we can try to catch Exception. But why Throwable? Do you think it makes any sense?
There is almost never a good reason to do this. The contract of toString() does not say it’s permissible to throw an exception from that method. Any code which throws an exception is broken code, and such an exception needs to be exposed and fixed, not suppressed.
In the case where you are converting some “bad” object from a library which is out of your control to a String, it might be appropriate to write catch (RuntimeExcepton e), but such a catch should be accompanied by comments which describe in detail why it is necessary, because under normal circumstances, it is not needed.
Rogue exception-throwing toString methods aside, note that Java already has at least two “safe” ways to convert a possibly null value to a String:
Objects.toString(obj, null)
String.valueOf(obj)
…so I would question whether the safeToString method should exist at all.
There are rare cases where you might want to catch an Error like this. In general it's a bad idea however, in this case it might make sense as this is generally for logging/debugging purposes and not used directly by the application.
I would prefer something more informative such as
private static String safeToString(Object obj) {
if (obj == null) return null;
try {
return obj.toString();
} catch (Throwable t) {
return obj.getClass() + ".toString() threw " + t;
}
}
e.g.
class Element {
Object data;
Element e;
public String toString() {
return data + (e == null ? "" : e.toString());
}
}
Element e = new Element();
e.data = "hi";
e.e = e; // oops
System.out.println("e: " + safeToString(e)); // doesn't kill the thread or JVM.
Throwable is the parent class of Exception and Error.
It is normally a bad idea to try and catch Error, as it is designed to not be caught.
Catching Throwable is just the overachieved and counterproductive version of catching Exception. Nonetheless, if for some reason you created another kind of Throwable you want to catch along with an Exception, that could be a way to do that in a single try/catch block. Not that it would be a clean way to do so, but it would work.
EDIT for the TL;DR : in most cases, catch Exception instead of Throwable.
It is incorrect to catch any Throwable and then continue execution since it includes Error, which is meant to be fatal:
From the Javadocs:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
That is, some Errors can be recovered (e.g. LinkageError), but others not so much.
But catching Exception might be a valid use-case for example in logging code where you don't want the execution to break simply because a call to toString() fails:
private static String safeToString(Object obj) {
try {
return obj == null ? "null" : obj.toString();
} catch (Exception e) {
return "<exception: " + e + ">";
}
}
I am writing a Java code to fetch the object information by passing the object id. My case will be like this:
1. Its not necessary that all Object ID's have information which means returns null.
2. But If the ID has a information, then I will return the object. So I am doing null check here.
If I write a else condition which throws the KalturaApiException, then its throwing the exception saying EntryId not found and stopping the execution there. My problem is it should continue with the positive flow and should log all the ids with no information. How to handle this scenario and how to catch this exception. Please help me resolving this. Thanks in advance.
try {
entryInfo = getMedia(entry);
if (entryInfo != null) {
//Here I am retrieving all the information from the object and setting to one more object.
}
}catch(KalturaApiException e){
e.getMessage();
}
Inside getMedia method:
try {
entryInfo = mediaService.get(entryId);
if (entryInfo != null) {
return entryInfo;
}
} catch (KalturaApiException e) {
e.getMessage();
}
return entryInfo;
If i understand you right, mediaService.get also throw KalturaApiException.
I think you don't need to worry about it. So inside getMedia you can just
return mediaService.get(entryId);
null also an object and you do null check in the other method. Exception also will be catched in your first method. (don't forget sign getMedia(long id) throw KalturaApiException {...})
try {
entryInfo = getMedia(entry);
if (entryInfo != null) {
// do something
}
}catch(KalturaApiException e){
e.getMessage(); //log information, it's better to use logger (log4j for example)
}
I'm a beginner in java writing an frontend for a webservice.I have to validate the input to get useful error messages for the user.Currently it works this way:
public Object zipVal(String zip)
{
try
{
if (zip.length() == 5)
{
val.setZip(Integer.parseInt(zip));
return val.getZip();
} else
{
return lengthError;
}
} catch (NumberFormatException e)
{
return formatError;
}
}
for zip Codes.Using Objects to declare the return type is not what I want tho(and is afaik discouraged),but I'm not sure how I should handle wrong inputs other than that.Should I just return null for every Exception and invalid input and handle such things in another method?
Edit:Added something to actually throw an Exception...
Yeah, exception handling might be one of the trickier things to consider (if one comes from a C programming background for example, where we used to be happy with < 0 return code for indicating erroneous program flow).
Normally you are pretty safe off by catching other API:s you integrate with and encapsulate them in your own exception (sort of masking them away), but by doing so don't forget to chain the original exception into your own with this constructor (and/or derivatives of such):
public MyException(final String message, final Throwable cause) {
super(message, cause);
}
One surely see alot of:
catch (Exception) {
return null;
}
and such in code as well, I wouldn't say that this is "good" object orientation, but it is still common and could be used in special occasions.
And also, its usually very important what you do (how to handle) when you catch the exception, someone told me that programing is 90% about error control and 10% about functionality :)
Here are some tutorials/resources:
http://docs.oracle.com/javase/tutorial/essential/exceptions/
http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/
If you are returning a value, then there is no need to handle the exception. It is better you declare that the method may throw the exception.
NumberFormatException is a RunTimeException. So if you wish to handle it, then better return an invalid zip (say -1) to let the caller know that something went wrong.
Otherwise, declare that you will throw a Custom Exception if NFE occurs.
This snippet may be useful.
public int setZipVal(String zip) // throws CustomException
{
try
{
if (zip.length() == 5)
{
val.setZip(Integer.parseInt(zip));
return val.getZip();
}
} catch (NumberFormatException e)
{
// Log the error and return invalid zip
return -1;
// OR throw custom exception
throw new CustomException("Length Error"));
}
}
I am looking at a code base where the domain model consists of many nested member variables.
Consider this scenario
private static String getSomeStringRepresentation(A input) {
String result = "";
try {
result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
} catch (NullPointerException e) {
Logger.logDebug(e.getMessage());
}
return result;
}
In this call chain, any method call can result in a NullPointerException. Is it correct to handle it with a catch clause in this case? Is this a case where "it is possible to handle the exception" ?
Edit
The case of checking for null four times is really ugly. Don't you consider catching the NPE is justified in this case?
The problem here is calling some method on a object that possibly could be null.
Why don't you check for null rather than putting a catch block? Catching NullPointerException isn't considered good practice.
If catching null pointer exception is not a good practice, is catching exception a good one?
also
Is Catching a Null Pointer Exception a Code Smell?
Catching a NullPointerException is not a good practice without a serious reason:
Rather check for null object like this:
private static String getSomeStringRepresentation(A input) {
String result = "";
try {
if(input != null && input.getTypeA() != null && input.getTypeA().getTypeAInfo() != null && getTypeAInfo().get(0) != null){
result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
}
} catch (NullPointerException e) {
Logger.logDebug(e.getMessage());
}
return result;
}
Here is a possible duplicate on the subject.
NPEs are just an error in the code and should therefore not be catched - they should be fixed.
NullPointerException indicates a programming error, catching it is wrong. Instead of catching it fix bugs in your program.
If I have a set method in which I want to modify some values,
if an user enter wrong values which is the best exception to throw to indicate that failure?
public void setSomething(int d) throws ....
{
if (d < 10 && d >= 0)
{
// ok do something
}
else throw new ... // throw some exception
}
I'd go for IllegalArgumentException.
Thrown to indicate that a method has been passed an illegal or
inappropriate argument.
EDIT
Another note:
Instead of
if (conditionIsTrue) {
doThis();
doThat();
} else {
throw new IllegalArgumentException();
}
write:
if (conditionNotTrue) {
throw new IllegalArgumentException();
}
doThis();
doThat();
(Though this advice may be controversial ;-)).
I agree with #Code Monkey about creating your own InvalidArgumentException, but his implementation doesn't show all the advantages it provides.
1) You can add convenience methods to simplify argument checking. For example:
InvalidArgumentException.throwIfNullOrBlank(someString, "someString");
vs.
if (someString == null || someString.trim().isEmpty()) {
throw new IllegalArgumentException("someString is null or blank");
}
2) You can write unit tests that confirm which argument was invalid. If you throw IllegalArgumentException, your unit test can't confirm that it was thrown for the reason you expect it to be thrown. You can't even tell that it was thrown by your own code.
try {
someClass.someMethod(someValue);
Assert.fail("Should have thrown an InvalidArgumentException");
} catch (InvalidArgumentException e) {
Assert.assertEquals("someValue", e.getArgumentName());
}
3) You can tell that the exception was thrown from within your own code. (This is a minor point that doesn't have much practical advantage)
If the number is an index, you could use IndexOutOfBoundsException. Otherwise, as Oliver says, IllegalArgumentException.
Don't be afraid to create a subclass of IllegalArgumentException to be more precise about the problem. Any catch blocks written for IllegalArgumentException will still catch it, but the stack trace will be slightly more informative.