Null pointer exception in java ArrayList - java

I am just beginning java programming. I have got a Null Pointer exception problem in the array List
My code is below
ArrayList<Arpaymentitem> arpaymentitemsList= jb.getArpaymentitems();
arpaymentitemsList.removeAll(Collections.singleton(null));
try {
for(Arpaymentitem arpaymentitem:arpaymentitemsList)
{
if (arpaymentitem.getInvoicekey()!=null) {
statement2.setString(1,arpaymentitem.getInvoicekey());
}
if(arpaymentitem.getInvoicekey() != null)
{
statement2.setString(2,arpaymentitem.getAmount());
}
}
statement2.addBatch();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting null pointer exception error in the FOR statement. I am sure there are some null values in the list. To ignore the null values I have introduced a step
ArrayList<Arpaymentitem> arpaymentitemsList= jb.getArpaymentitems();
arpaymentitemsList.removeAll(Collections.singleton(null)); --> remove nulls
The NPE I got is
java.lang.NullPointerException
at payment.Intacct_Payment.main(Intacct_Payment.java:169) and the line is
for(Arpaymentitem arpaymentitem:arpaymentitemsList)
The problem still persists. What am I doing wrong here.

Can you try this follwing steps and give a feedback
ArrayList<Arpaymentitem> arpaymentitemsList = new ArrayList<>();
if (jb.getArpaymentitems().size()> 0)
{
for (Arpaymentitem arpaymentitem : jb.getArpaymentitems())
{
System.out.println("Description: ...");
arpaymentitemsList.add(arpaymentitem)
}
}
//The Rest of the code

Related

chain exception in catch block

I have the following java code :
public void someMethod(){
try{
// some code which generates Exception
}catch(Exception ex1) {
try{
// The code inside this method can also throw some Exception
myRollBackMethodForUndoingSomeChanges();
}catch(Exception ex2){
// I want to add inside `ex2` the history of `ex1` too
// Surely , I cannot set cause of `ex2` as `ex1` as `ex2`
// can be caused by it's own reasons.
// I dont want `ex1` details to be lost if I just throw `ex2` from my method
}
}
}
How to do it ?
EDIT : Actually this happens in my service layer and I have controller advice for logging. Hence I don't want to add 2 loggers here.
You can add ex1 to the supressed exceptions in ex2 via the method addSuppressed before rethrowing it.
Quick code example:
public static void main(final String[] args) {
try {
throw new IllegalArgumentException("Illegal Argument 1!");
} catch (final RuntimeException ex1) {
try {
throw new IllegalStateException("Illegal State 2!");
} catch (final RuntimeException ex2) {
ex2.addSuppressed(ex1);
throw ex2;
}
}
}
will produce the exception output:
Exception in thread "main" java.lang.IllegalStateException: Illegal State 2!
at package.main(Main.java:26)
Suppressed: java.lang.IllegalArgumentException: Illegal Argument 1!
at package.main(Main.java:20)

Catching Exception with JUnit #Test(expected=Exception.Class)

I am writing a test case using JUnit and I am trying to catch an Exception using #Test(expected=Exception.Class). For some reason I am unable to catch the exception. If I pass null it would throw NullPointerException and the test catches it because Exception is the parent class but on my Coverage report the exception is still not covered.
Method under test:
private static final String CONTENT_LENGTH = "Content-Length";
protected long getContentLength( MultivaluedMap<String, String> headers ) {
String length = headers.getFirst( CONTENT_LENGTH );
if( length != null ) {
try {
return Long.valueOf( length );
} catch( Exception e ) {}
}
return 0;
}
JUnit test case:
#Test(expected=Exception.class)
public void testGetContentLength() {
new TestBaseMessageBodyReader().getContentLength(null);
}
Any help would be appreciated.
Thanks
Catching generic exception is bad practice and even worse to catch an exception and do nothing. in your try catch you should catch NumberFormatException which is what Long.valueOf has the potential of throwing. Even then your jUnit will not never catch the exception because you are catching the exception but not doing anything with it, the method would always return 0 as it's currently written (provided you're not passing null)
Here is some code that would catch the exception on your unit test. I'd create two unit tests, one to catch your the first exception and one to catch the second.
protected long getContentLength(MultivaluedMap<String, String> headers)
{
if(null == headers)
{
throw new SomeCustomException("some message");
}
Long returnValue = 0;
String length = headers.getFirst(CONTENT_LENGTH);
try
{
returnValue = Long.valueOf(length);
}
catch (NumberFormatException e) {
// if you can recover handle it here
// if you can't recover then break the app
throw new SomeOtherCustomException("some other message");
}
return returnValue;
}

java handle return exception

The following code is supposed to return the last value in arraylist if it has one, if not, how could I return the exception?
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
}
}
arrl here is ArrayList
I excuted above code and received "error: missing return statement"
You have return statement in your try{} but not in your catch(){}, this gives you the exception. You can include the return in both or return after the try catch.
public int getLast() {
Object o=null;
try {
o=arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
}
return o;
}
Also to return the exception back to the caller you need to rethrow it from your method, or not catch it at all
catch (Exception e) {
System.out.println("Caught "+ e);
throw e;
}
or
public int getLast() {
return arrl.get(arrl.size() - 1);
}
But I doubt any exception being thrown from this statement except for IndexOutOfBoundsException
You don't return an exception.. You throw it back to the caller.
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
throw e;
}
}
Your code gives you compilation error because you are not returning anything in catch block. throwing would be good enough.
Alternatively, don't catch it, any uncaught exceptions will be automatically thrown back to the caller. So below code would also throw the exception back to the calling method.
public int getLast() throws Exception {
return arrl.get(arrl.size() - 1);
}
There's really no good reason for the try/catch block here at all. Just let the NPE or AIOOBE be thrown to the caller and let him deal with them.
You are getting this error because if the first return in the try-part didn't work the compiler doesn't know what it should return instead. You need either another return or exception rethrow in the catch-part:
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
// You need to return something here or rethrow the e...
}
// or return something here.
}
...but this kind of logic is bad any way and this function shouldn't throw exceptions at all. I'd be better to check it the array has any items before getting the last one. If you run this in a loop the performace might be really bad if the error is thrown frequently.
public int getLast() {
if (arrl != null && arrl.size() > 0) {
return arrl.get(arrl.size() - 1);
}
else {
return -1;
}
}
or
public Integer getLast() {
if (arrl != null && arrl.size() > 0) {
return arrl.get(arrl.size() - 1);
}
else {
return null;
}
}
In this scenario, the only exceptions that may be raised are NPE due to arrl being null and an indexing error if the list is empty. If the class is properly initialised, the NPE shouldn't happen at all. The other exception is a client error, which may be passed on to the caller. Alternatively, one might consider returning null (after changing int to Integer):
public Integer getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (IndexOutOfBoundsException ioobe) {
return null;
}
}
There is the possability that your method can not return a value (for what reasons ever). In this case you should use now java.lang.Optional (Java-8) as return type:
public Optional<Integer> getLast() {
try {
return Optional<T>.ofNullable(arrl.get(arrl.size() - 1));
} catch (Exception e) {
e.printStackTrace();
return Optional.empty();
}
}
This way you will force the user of your method to deal with the situation of not having a result to be returned. (BTW: you should not catch Exception, mostly never. Instead take care that arrl is not null and arrl.size() is within the limits. Handling exceptions is for the... umm exeptional cases, not to be used as control statement.)

Why do I get NoSuchElementException even though I am catching it in cucumber stepdefinition?

#When("^user clicks linkedin button of the first news item$")
public void user_clicks_linkedin_button_of_the_first_news_item()
{
try
{
firstSocialShareElement = driver.findElement(By.className("social-share-linkedin"));
if(firstSocialShareElement!=null && firstSocialShareElement.isDisplayed())
{
firstSocialShareElement.click();
}
}
catch(NoSuchElementException e)
{
}
}
It turns out it was a simple case of class name conflict.
Since i didn't specify the full qualified name of the exception as org.openqa.selenium. NoSuchElementException
It was considering it to be java.util. NoSuchElementException
and hence the exception was not getting caught.
Now the problem is resolved.
try
{
firstSocialShareElement = driver.findElement(By.className("social-share-linkedin"));
if(firstSocialShareElement!=null && firstSocialShareElement.isDisplayed())
{
firstSocialShareElement.click();
}
}
catch(org.openqa.selenium. NoSuchElementException e)
{
}

Exception Handling In Android Unit Test Case

I am doing Android Unit Test Case Execution and for Negative Test Case I should get exception, but for some API's Exception is not caught.
Please do find the example below:
public void testInsertSenderType_n() {
DBSms obj = new DBSms(getContext());
obj.open();
int i =0;
int a =0;
boolean result = true;
i=obj.GetToatlCount();
obj.insertSmsText(i+1,"Hello to testInsertSenderType_n");
a=obj.TotalcountSms("Inbox");
try
{
obj.insertSenderType(-100, "Richard", "Inbox", 0);
}
catch (Exception e)
{
// TODO: handle exception
result = false;
}
assertEquals(a,obj.TotalcountSms("Inbox"));
assertEquals(false,result);
obj.close();
}
Here in, obj.insertSenderType(-100, "Richard", "Inbox", 0); should throw an exception. But it is not thrown.
Please do guide where can I be Wrong.
I use following method to expect proper exception:
try {
doSomethingToProvokeException();
fail("there ought to be an exception dude, but was not");
} catch(ExeptionIHaveProvoked ex) {
doAssertionnsonThrowsException
}
You do not need variables to keeps exception state. As for why no exception is thrown in your code - nobody cann tell it to you, unless you provide source of object.

Categories