Catching the NumberFormatException - java

Below is the class somebody else wrote.
The problem that I am facing is that when it get's into the parse method with null as the rawString, it is throwing NumberFormatException.
So what I was thinking to do is, I should catch that NumberFormatException and set the value itself as null. So the way I did is right?
public class ByteAttr {
#JExType(sequence = 1)
private Byte value;
public static ByteAttr parse(String rawString) {
ByteAttr attr = new ByteAttr();
try {
attr.setValue(Byte.valueOf(rawString));
} catch (NumberFormatException nfEx) {
attr.setValue(null);
}
return attr;
}
public Byte getValue() {
return this.value;
}
public void setValue(Byte value) {
this.value = value;
}
}

The correct approach depends on what you want to accomplish in the program.
If it makes sense for ByteAttr.getValue() to return null later in your program, then your approach could work.
However, you need to consider whether you should be throwing an exception if parse is called with an indecipherable argument (including null). An alternative is to catch the NumberFormatException and throw a different exception that has semantic meaning in your program.
public static ByteAttr parse(String rawString) throws BadAttributeException {
ByteAttr attr = new ByteAttr();
try {
attr.setValue(Byte.valueOf(rawString));
} catch (NumberFormatException nfEx) {
throw new BadAttributeException(nfEx); // wrap original exception
}
return attr;
}
Another technique is to pass a default value to parse for those cases when rawString is indecipherable:
public static ByteAttr parse(String rawString, Byte defaultValue) {
ByteAttr attr = new ByteAttr();
try {
attr.setValue(Byte.valueOf(rawString));
} catch (NumberFormatException nfEx) {
attr.setValue(default);
}
return attr;
}

You need to do four things:
Decide what an unparsable number string means in the context in which you will be using the method. Does it mean an internal problem in the program? A corrupt file? A user typo? Nothing wrong but that string needs to be handled differently?
Decide the best way to handle it, taking that into account. Almost always, if the error is triggered by external input you need to report it back. Substituting null may be a good way of handling it.
Document what you decide to do. If a method is going to return null with some specific meaning, that needs to be written down as comments, preferably Javadoc commments.
Implement your decision.
I get the impression, perhaps unfairly, that you have jumped straight to step 4, without thinking through the possible causes and proper reporting of the problem.

You can add an early exit with a condition like:
if (rawString != null) {
return attr; // or other value you prefer
}
You can also make sure the caller of the parse method test for null value and avoid calling parse when it is.

It depends on the tolerance to null values in your application. If you expect the users to not pass null string to the parse() method, then you should do a defensive null check and throw an exception.
if (null == rawString) {
throw new CustomException("rawString cannot be null");
}
The same would apply to the catch block for NumberFormatException, where instead of silently setting the value of Byte attribute to null, you should throw an exception with appropriate message.
But if null is perfectly acceptable, then you should perform a defensive null check and set the Byte attribute to null. The NumberFormatException should certainly be NOT suppressed, IMHO.

Related

Catch exception from toString method in Java

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 + ">";
}
}

Checking for NullPointerException at the beginning of every method

Is it better to wait for a null pointer exception to happen?
public void doSomething(String str) {
Double val = Double.parseDouble(str); // Null pointer exception thrown here
// Other code
}
Or is it better to check every time for it, as early as possible?
public void doSomething(String str) {
if (str == null)
throw new NullPointerException(); // Null pointer exception thrown here
Double val = Double.parseDouble(str); // Other code
}
I would recommend using an assert clause. I think his response best answers your question
Avoiding != null statements
I would indicate in your method if str can be null or not with the #Nullable keyword. If you are disallowing the str variable to be null then do not do any null checking. You should instead check if str is null before calling doSomething. If str is allowed to be null then wrap it in a null check and do whatever you deem to be appropriate if the variable is null.
public void doSomething(#Nullable String str) {
if (str != null) {
Double val = Double.parseDouble(str);
// other code
}
else {
// return or do something else
}
}
Or..
public void doSomething(#Nullable String str) {
if (str == null) {
return;
}
Double val = Double.parseDouble(str);
// other code
}
I would not recommend throwing a null pointer error unless the application cannot continue without the str variable. You want to capture exceptions so your application doesn't crash not allow them to crash your application.
In that case it doesn't make much difference as parseDouble will throw a NPE. In a more general case, since Java 7, you can use:
Objects.requireNonNull(str); //throws NPE if str is null
//rest of the code
There no different code. You should throw some specific exception.
And sometimes null is legal value.
Sometimes it is usual to define something like a method contract.
I am doing this via Spring Asserts:
org.springframework.util.Assert;
Assertion utility class that assists in validating arguments. Useful
for identifying programmer errors early and clearly at runtime.
For example, if the contract of a public method states it does not
allow null arguments, Assert can be used to validate that contract.
Doing this clearly indicates a contract violation when it occurs and
protects the class's invariants.
Typically used to validate method arguments rather than configuration
properties, to check for cases that are usually programmer errors
rather than configuration errors. In contrast to config initialization
code, there is usally no point in falling back to defaults in such
methods.
This class is similar to JUnit's assertion library. If an argument
value is deemed invalid, an IllegalArgumentException is thrown
(typically).
In your case:
public void doSomething(String str) {
Assert.notNull(str);
Double val = Double.parseDouble(str); // Nullpointer not possible here if the contract was not injured.
// Other code
}
If a null value is passed by any developer the contract was not fullfilled and a IlligalArgumentException is thrown.
Easy testable via Junit:
/**
* Check case that passed string is null.
*/
#Test(expected = IllegalArgumentException.class)
public void testDoSomething_StringIsNull() {
mClassUnderTest.doSomething(null);
}

How to handle errors properly

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"));
}
}

Breaking a method before having a return value

Is there any solution i can break a running method which is supposed to return an int[] or whatever but !without! any return value.
I thought that might work with some exception but i didn't find a propper way. To be more specific i want something which tries to find out if a certain field of an object was set and if yes return it and if no returns a message which tells me that the input wasn't made so far.
something like this:
public int[] returnArray(){
if(array_was_set==true) return the array;
else show message that it wasnt set and quit the method without any return value;
}
One way of doing that, return null and make the caller decide , if the caller gets a nun-null (or maybe a non-empty) array it will process it in some way and if the caller get an empty or null array it could print a message.
I would recommend against using exceptions as a substitute for return values see this question to know more about when to throw an exception.
There are three options to choose from, depending on your scenario:
Use return value of null (and document it)
Throw an exception with a detailed message. I would use this version only for exceptional cases such as illegal API usage or a logical error situation(bug).
Return a wrapper class, containing both a return value and some other message, when relevant
Edit: Another 2 options:
Use polymorphism - Return type can be Result, and concrete subclasses can be NoResult and DataResult.
Instead of returning null, return a constant value defined as:
static final NO_RESULT = new int[0];
Later you can check the returned value against it (using == condition).
You should be able to do it by raising an exception. Just use the message in the exception's constructor.
However, exceptions are relatively expensive and if this isn't really an error condition you should consider doing something else, such as returning null to indicate there is nothing to return.
Yes better way is use Exception
example
public static void main(String[] args) {
try {
new Result().returnArray(false) ;
} catch (Exception e) {
}
}
.
public int[] returnArray(boolean input) throws Exception {
if(input) {
return new int[]{1};
}
else {
System.out.println("Not match");
throw new Exception();
}
}
When you declare in the method signature that it is returning a data type then it must have a return statement which returns that specific type value. Otherwise you will get compile-time error.
The only exception when a method can avoid return statement even though it has return type is when there is an infinite loop or an exception is thrown. Otherwise return statement is compulsory.
Coming to your question, you can easily achieve what you are doing. If you want to terminate at a particular point as per your requirement just say,
return null;
It will work for all the data types except for primitive types in which case you need to do type casting to Wrapper class types appropriately.
public int[] returnArr() {
if(some condition)
return SomeIntArray;
else
return null;
}
public int returnInt() {
if(some condition)
return 2;
else
return (Integer)null;
}

How would I go about throwing an "optional" exception?

I've got this method I'm working on (I think that's the name) and it essentially tries to match a part of a string and then return the proceeding part of the string - that part I've got, easy stuff. The method is of type String.
When my method fails to find the pattern in the string I want it to return an empty string. I also want to send something along with the empty string to go "hey, I didn't find your key" but I want this to be optional.
This is essentially what I want the method to do:
public static String getKey(String key) throws KeyNotFoundException {
if (key.equals("something")) {
return "great";
} else {
throw new KeyNotFoundException();
return "";
}
}
But the problem with this code is that the return ""; is obviously unreachable due to throw new KeyNotFoundException();.
If I was going to call this method I'd have to use the try {} catch(KeyNotFoundException knf) {} block. It's this block that I want to make optional however.
If I choose to be oblivious to the fact the key was not found (e.g. don't use try catch) then I just want to be given the empty string on return.
But I also want to be able to surround it with a try-catch block if I need to know whether the key was found for my operation to complete correctly.
I think I'm going about this the wrong way but I can't seem to figure out an alternative (new to Java), could anyone shred some light on this please?
The usual way to do this would be to write two methods, one which returns a default value, and one which throws an exception. You can have one of these call the other, to avoid duplication:
public static String getKey(String key) throws KeyNotFoundException {
String value = getOptionalKey(key);
if (value.equals("")) throw new KeyNotFoundException(key);
return value;
}
public static String getOptionalKey(String key) {
if (key.equals("something")) {
return "great";
} else {
return "";
}
}
The caller can then choose which one to call, based on their needs:
String value = getOptionalKey("uma"); // oblivious
try {
String value = getKey("uma"); // cognisant
}
catch (KeyNotFoundException e) {
// panic
}
You should either use return values or exceptions to denote an error condition, but not both.
Generally, if you anticipate that something can go wrong, use a return value, and if the error is exceptional, throw an exception (as the name suggests).
By definition, an exception disrupts the normal program flow. The exception "bubbles up" until someone catches it or the thread terminates.
You can't do exactly what you're trying, but you have a couple options. You could write a "safe" version of the method that returns a default value if the key isn't found, like you're trying to do, and have a separate method that will throw the exception if the key isn't found.
Another option, if you've defined KeyNotFoundException yourself, would be to derive from RuntimeException instead of simply Exception. Then, you could remove the throws declaration from your method signature and not publish the fact that the method could throw an exception.
You can't, however, throw an exception from the method AND return a value from the method.
Another way you could deal with optional return values is to use Java 8's Optional class, and let the caller decide what to do when the value is not present:
public static Optional<String> getOptionalKey(String key) {
if (key.equals("something")) {
return Optional.of("great");
} else {
return Optional.empty();
}
}
You could combine it with the multiple methods approach discussed in other answers:
public static String getKey(String key) throws KeyNotFoundException {
return getOptionalKey(key).orElseThrow(() -> new KeyNotFoundException(key));
}
What about if you create your own Exception (extend Exception) which will have a constructor that takes a String or whatever you want to send to it (like error code or statement)?
Then you can have a getter method within your Custom Exception that will be used to "get" whatever the error message was.
nope. a method can only end with returning a value/end or return; if it is void OR throw an exception.
From what I understand of what you want to achieve, you could use a void returning method and provide a reference of a special object in argument. you would then set a field of this object to the result you want to 'return' and throw the exception.
Something like
class final ResultHoder {
String result;
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return this.result;
}
}
public static void getKey(String key, ResultHolder result) throws KeyNotFoundException {
if (key.equals("something")) {
result.setResult("great");
return;
} else {
result.setResult("");
throw new KeyNotFoundException();
}
}

Categories

Resources