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.
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'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.
I have 2 classes, one that implements a double lookup( int i);
and one where I use that lookup(int i) in solving a question, or in this case printing the lookup values. This case is for an array.
So I read the exception documentation or google/textbook and come with the following code:
public double lookup(int i) throws Exception
{
if( i > numItems)
throw new Exception("out of bounds");
return items[i];
}
and take it over to my class and try to print my set, where set is a name of the
object type I define in the class above.
public void print()
{
for (int i = 0; i < set.size() - 1; i++)
{
System.out.print(set.lookup(i) + ",");
}
System.out.print(set.lookup(set.size()));
}
I'm using two print()'s to avoid the last "," in the print, but am getting an
unhandled exception Exception (my exception's name was Exception)
I think I have to catch my exception in my print() but cannot find the correct formatting online. Do I have to write
catch exception Exception? because that gives me a syntax error saying invalid type on catch.
Sources like
http://docs.oracle.com/javase/tutorial/essential/exceptions/
are of little help to me, I'm can't seem to grasp what the text is telling me. I'm also having trouble finding sources with multiple examples where I can actually understand the coding in the examples.
so could anybody give me a source/example for the above catch phrase and perhaps a decent source of examples for new Java programmers? my book is horrendous and I cannot seem to find an understandable example for the above catch phrase online.
I wouldn't throw Exception ever.
In your case, IndexOutOfBoundException or InvalidArgumentException would eb a better choice. As these are not checked Exceptions, you don't need to catch them.
public double lookup(int i) {
if(i >= numItems) // assuming numItems is not items.length
throw new IndexOutOfBoundException("out of bounds " + i + " >= " + numItems);
return items[i];
}
Note: the check should be >=
Your print() method will now compile unchanged.
What is Exception?
Exceptions are for exceptional conditions. Conditions that normally do not occur. Take an example you went to withdraw money and your account has 100 balance and you asked for 200 then ATM should tell you that you have insufficient balance.
Types of Exceptions
Checked Exception
These are conditions where application wants to recover from it. Like example given above application will give you error and will continue working.
Error
This is an exceptional condition which is external to application. We say OutOfMemoryError when there isn't enough memory available and application can not recover from it.
Runtime Exception /Unchecked Exception
These exceptions are applications exception but in this case application can not recover from it. E.g NullpointerException if value is null and you try do something nasty with it.
so of above three only checked exceptions need to be cached.
How to throw and Catch Checked Exception
Exception or any subclass of Exception is a checked exception. A checked exception can be thrown using throw clause. Once you throw an exception it becomes mandatory for you to include that in method declaration using throws clause.
So whoever want to use this method will now have to handle that exception. Handling exception means invoking alternative flows. Like in our case we displayed text to user "Error Invalid account number."
Calling function can also choose to propagate exceptions by adding throws clause for those exceptions which are thrown by method it is calling.
Generate:
public static double withdraw(int i) throws Exception {
if (i <= 0)// Out of bounds
throw new Exception("Invalid Account Number");
return 0.0;// something;
}
Handle:
try {
withdraw(0);
} catch (Exception e) {
// do something with exception here.
// Log the exception
System.out.println("Error Invalid account number.");
}
Propagate:
public static double callWithdraw(int i) throws Exception {//Propagate exceptions
return withdraw(i);
}
Try this
try
{
print(); //print() needs to throw the same exception
} catch(Exception e)
{
//handle exception
System.err.println(e.getMessage()+"\n\n"+e.printStackTrace());
}
//finally {
// cleanup here if you like
// }
or this
public void print()
{
for (int i = 0; i < set.size() - 1; i++)
{
try
{
System.out.print(set.lookup(i) + ",");
} catch(Exception e)
{
//handle it here
}
}
System.out.print(set.lookup(set.size()));
}
Do note that using "throws" is kind of a easy way out; it's a cheap delegation that sometimes makes coding easier... if you can, you should try to always use try/catch instead of throws.
Just be aware that whenever you use something with "throws" eventually you will have to put that in a try/catch block and deal with it properly.
Generally to denote improper arguments passed into your method, use IllegalArgumentException which is a RuntimeException and should not be caught.
In this specific case you don't have to write any extra code, the ArrayIndexOutOfBoundsException should take care of improper array access.
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.
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.