Java Positive flow and negative flow exception handling - java

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

Related

How check if an Attribute(object) is null in Java

I need specific data for a report, then I gettin all information from a parent object
Object1
It has many attributes, object attributes
Object11, Object12, Object13, attr1, attr2...
The attributes has many attributes too
Object111, Object131, Object132,..
by now I got 5 level data attributes.
When I send information to my report it says, Error: cause:null
object1.getIdObject11().getIdObject111().getDescription;
It trows error because Object111 is null
I tried using
object1.getIdObject11().getIdObject111().getDescription==null?'':object1.getIdObject11().getIdObject111().getDescription;
but it only verify if description is null, and throws the same error
Then I tried to verify Object
if(object1.getIdObject11().getIdObject111() == null) {
var = object1.getIdObject11().getIdObject111().getDescription;
} else {
var = "";
}
But when Object11 is null, it throws same error.
I don't think its a good way doing this for each attribute (have to get like 30 attributes)
if(object1.getIdObject11()!=null) {
if(object1.getIdObject11().getIdObject111()!=null) {
if(object1.getIdObject11().getIdObject111().getIdObject1111()!=null) {
//...
}
}
}
I want to verify if is there a null object and set '' (blank) if it is, with no such a large code(because the gotten params are set inside a report, mixed with letter).
reportline1 = "Area: "+object1.getIdObject11().getIdObject111().getName;
You code breaks Demeter's law. That's why it's better to refactor the design itself.
As a workaround, you can use Optional
var = Optional.ofNullable(object1)
.map(o -> o.getIdObject11())
.map(o -> o.getIdObject111())
.map(o -> o.getDescription())
.orElse("")
The way I would probably do this to extend the functionality of the code easily in the future might take a bit of writing in the beginning but will be easily usable forever.
I would create a new method in your parent class called hasNull that returns a boolean like so:
public boolean hasNull()
{
boolean hasANull = false;
//Call another hasNull() inside of object11 which in turns calls hasNull() in object111 etc.
//If any of the calls return with a true/null value set hasANull to true
return hasANull;
}
This in turn checks to see if the current objects it contains are null. If one of the class variables is another custom class you created you can then add another hasNull into that one and keep going until you get to the lowest level where you can do a specific operation when the value is null such as set it to "".
After implementing this you will be able to just be able to use it like this any time you need it:
if (!object1.hasNull())
{
//Do whatever you want if there are no null values
}
else
{
//Do whatever you want if there is a null value
}
You can also make this a void method if you only want it to toggle the values on the lowest level, and do not need to do anything in either case.
I prefer the solution that gave dehasi.
But you can also do something like that:
getOrElse(() -> object1.getIdObject11().getIdObject111().getDescription(), "")
Where getOrElse is:
public static <T> T getOrElse(Supplier<T> getter, T elseValue) {
try {
return getter.get();
} catch (Exception e) {
// log or do something with it
}
return elseValue;
}
It may be controversial becaouse you use Exception to do this.
You can use this code to check if your object has a null attribute, the object is myclass;
for (Field f : myclass.getClass().getDeclaredFields()) {
f.setAccessible(true);
try {
if (Objects.isNull(f.get(myclass))) {
isLineContainsNull = true;
}
} catch (Exception e) {
log.error(e.getMessage());
}
}

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

Where's the "right place" to put return statement in try catch finally

End of try block, or after all blocks?
I read a lot of answers on stack overflow about what will happen in each case. However, I could not find out which one is the commonly accepted "corrected" place to return.
Object o = null;
try {
Connection c = getConnection();
o = c.getThing();
return o;
} catch (Exception e) {
//handle exception
return null;
} finally {
c.close();
}
vs
Object o = null;
try {
Connection c = getConnection();
o = c.getThing();
} catch (Exception e) {
//handle exception
return null;
} finally {
c.close();
}
return o;
It completely depends on what you are trying to do. See the following code for some examples of the possibilities (not all of which should be combined in any single piece of code!).
try {
// do something that may fail
return 0; // return a normal value
} catch(SomeException e) {
// maybe log an error
return -1 // maybe return a default or error value
} finally {
// maybe clean up resources
// finally will be executed even if you return in try or catch
// a return here will trump a return in try/catch. This is generally regarded as a bad idea
// see https://stackoverflow.com/questions/65035/does-finally-always-execute-in-java
}
return 1 // return a normal value here instead of in the try/catch.
// May be clearer than multiple return statements
// Also useful if return value does not depend on the try/catch outcome
Update for your updated question. It's partly a matter of preference, though there are significant reasons for each choice. Many people prefer a single point of return, so would do this:
Object o = null;
try {
Connection c = getConnection();
o = c.getThing();
} catch (Exception e) {
//handle exception; leave o as null
} finally {
c.close();
}
return o;
Although this sounds like it should be clearer, of course one still has to examine the code to determine what value(s) o may end up with, so the advantage isn't great.
However, the other options have the advantage that the returning of null is very explicit. This is good if you are one of the many programmers who consider returning null values to be generally a bad idea (see Tony Hoare's "billion dollar mistake").
Instead of returning null one can use "Optional", "Option" or "Maybe" types (available in e.g. Java 8, Scala, Haskell and the Functional Java library), or use the Null Object pattern.

Catching the NumberFormatException

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.

Is there a sense to handle nullpointer exception by such way?

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.

Categories

Resources