null pointer exception in retrieving contacts in j2me - java-me

I am having problem with this contact retrieving code. The function getContact() is retuning null.
private PIM pim;
private ContactList clist;
public ContactExtract(){
pim=PIM.getInstance();
try{
clist=(ContactList) pim.openPIMList(PIM.CONTACT_LIST,PIM.READ_ONLY);
}catch(Exception e){}
}
public Vector getContact(){
//ContactDetail cd[]= new ContactDetail[200];
Vector v=new Vector();
try{
Enumeration en=clist.items();
//String num=null;
//String temp[]=new String[2];
//int i=0;
while(en.hasMoreElements()){
Contact c=(Contact)en.nextElement();
v.addElement(c);
//temp=c.getStringArray(Contact.NAME, i);
//num=c.getString(Contact.TEL, i);
//cd[i]=new ContactDetail(temp[0],temp[1],num);
}
clist.close();
}catch(Exception e){}
return v;

Most likely reason for NPE you are getting is is that clist value is null in the getContact method. Most likely reason for this is, in turn, some exception that happens in ContactExtract() constructor.
But one would never know that for sure as long as you swallow exceptions. If you're interested, search the web for something like java swallow exceptions to learn in more details why this is bad.
Meanwhile, the most straightforward way to find out what happened is to add appropriate logging everywhere in your code, first of all in the catch blocks. Make sure there are no statements like catch(Exception e){} and your reward will be much easier understanding on what went wrong.
In constructor, replace empty catch block with something like:
catch(Exception e){
Sustem.out.println("exception in openPIMList: [" + e + "]");
}
In getContat method, do about the same, only with appropriate log message:
catch(Exception e){
Sustem.out.println("exception in getContact: [" + e + "]");
}
Then, re-run the code in emulator and look into its console to find out what went wrong.
Another thing worth adding in the code is checking, logging and handling for possible null values. In getContact() method, clist can be null and cause you all the kind of trouble but you don't even try to check and handle that.

Always try to print Exception e.
catch(Exception e)
{
e.printStackTrace();
}
You'll come to know what's wrong in the code.

Related

mockito, how to coverage test the catch block

Android app, Having a function calling another function, that function may throw
static string SOME_DEFINE_1 = "some_define_1";
......
void myFunc() {
try {
HashMap<String, String> data = new HashMap<>();
data.put("key_1", SOME_DEFINE_1);
otherObject.func(data);
} catch (Throwable ex){
Log.e(TAG, "+++ exception from otherObject.func(), "+ ex.toString());
// do something
anotherFunc();
}
}
How to test the catch block is called when unit testing the myFunc?
It isn't clear in your example where otherObject comes from, but in general, to test the exception handling blocks you need code that will throw the exception. In this example, one way may be to mock the otherObject and then use thenThrow to cause it to throw an exception when the func(data) method is called. You could use a spy of the class you are testing and stub the anotherFunc method so you can replace it with something else and then verify if it was invoked for the conditions you expect to throw the exception.
These articles show the general approach:
https://www.baeldung.com/mockito-spy - (number 4)
https://www.baeldung.com/mockito-exceptions
So in a pseudo-code example:
// arrange
myClassUnderTest = spy(TheClassUnderTest);
otherObject = mock(OtherObject);
doNothing().when(myClassUnderTest).anotherFunc();
doThrow(new RuntimeException("simulated exception")).when(otherObject).func(any());
// act
myClassUnderTest.myFunc();
// assert
verify(myClassUnderTest , times(1)).anotherFunc();

Will Quartz.net job will run on the next iteration even if there is any exception

Probably a stupid question... but here goes anyway...
I would like to know if the quartz.net job will be active to run on the next iteration though there is an exception( which is handled) in the current iteration. Can anyone please explain me if my understanding is correct?
public void Execute(IJobExecutionContext context)
{
_logProvider.Info("Started..");
try
{
_service.Calculate();
}
catch (Exception ex)
{
_logProvider.Error("Error " + ex);
}
}
Thanks
The simple answer is: yes, it will execute on next iteration.
Actually this is related to general .NET exception handling, rather then quartz.net behaviour:
if you have function that catches any exceptions - exceptions will not be visible outside of that function. In other words, code like
public void SomeMethod()
{
try
{
//some logic that can generate exception
}
catch (Exception ex)
{
}
}
is the same as
public void SomeMethod()
{
//some logic that NEVER generates the exception
}
In scope of quartz.net:
The only type of exception that you are allowed to throw from the execute method is JobExecutionException.
otherwise you will have unhandled exception in AppDomain. You can find more in Quartz.net Job unhandled exception behaviour SO question

Initialize a Guid variable which will be assigned later

I have to write event receivers for SharePoint lists (SharePoint 2013). For logging purposes, I am declaring my Guid variable (corresponding to a Project) globally and then assigning a value to it whenever required in the event receivers (Item Adding, Item Updating, etc...).
Below is the code sample:
public class ClassName : SPItemEventReceiver
{
Guid prjguid;
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
try
{
prjguid = new Guid(properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"].ToString());
.
.
.
}
catch (Exception ex)
{
// Exception Handling
WriteLog(prjguid + ex.message);
}
}
public void WriteLog(string message)
{
// Logging
}
}
This code throws en exception:
Object reference not set to an instance of an object.
Any possible explanations where I am going wrong ?
As you do not mention where this exception is thrown there are several possible reasons for this exception:
Possible reason 1:
If an exception is happening within your properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"].ToString()
call the prjguid variable will not get assigned.
Then in your catch WriteLog method you want to print out this *prjguid * variable.
This is where your variable can be null.
Inside your catch you could try to change your code to
catch (Exception ex)
{
// Exception Handling
if(prjguid != null)
{
WriteLog(prjguid + ex.message);
}else
{
WriteLog(ex.message);
}
}
Possible reason 2:
properties.Site.OpenWeb() returns null
Possible reason 3:
properties.Site.OpenWeb().AllProperties["MSPWAPROJUID"] returns null
For case 2 and 3 you have to seperate those calls an check for null for both parts.

Cobertura, how to coverage catch-clause which will never occur

i have the ambitious goal to get 100% test coverage in cobertura. How can i achieve this on this code? There will never be an exception because the file is on the classpath. Can i remove files fropm classpath with junit?
try {
InputStreamReader reader = new InputStreamReader(WsdlSource.class.getClassLoader().getResourceAsStream("stringresources/stringresources.properties"), "UTF-8");
try {
p.load(reader);
} finally {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
First of all, to be able to test things right you have to learn what what loose coupling is and what Mock Objects are.
Basically, it is never a good idea to create an object with new because you create a hard dependency between the class InputStreamReader and your logic.
If your object p implements some kind of an interface, it would be good if you pass the instance of it from outside of your logic. Some implementations of Mock Objects also allow you to mock a class but I would not recommend that.
For example if you write your code like that:
public myMethod(SomeKindOfInterface p, InputStreamReader reader) {
try {
p.load(reader);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch(IOException e) {
//intentionally left blank, nothing could be done upon exception on closing
}
}
}
Then in your JUnit you could use Mockito to mock the IOException.
InputStreamReader reader = new InputStreamReader(WsdlSource.class.getClassLoader().getResourceAsStream("stringresources/stringresources.properties"), "UTF-8");
SomeKindOfInterface mock = Mockito.mock(SomeKindOfInterface.class);
Mockito.when(mock.load(reader)).thenThrow(new IOException());
myInstance.myMethod(mock, reader);
This way you would have your catch block covered.

Pattern for implementing sync methods in terms of non-parallel Task (Translating/Unwrapping AggregateExceptions)

I have an Async method returning a Task.
I also wish to offer a synchronous equivalent, but I don't want consumers of it to have to go unpacking AggregateExceptions.
Now I understand that the whole idea is that you couldn't arbitrarily pick one in a general way, and I know I could go read loads more Stephen Toub articles (I will, but not now) and I'll understand it all and can decide for myself.
In the interim, I want to use the fact that my tasks are actually just chained 'workflows' without parallelism, just intervening Waits (no, not TPL DataFlow) which shouldnt not result in more than one exception. In that case, would it be appropriate to handle as follows:
CallAsync().Wait();
}
catch( AggregateException ae)
{
throw ae.Flatten().First()
or am I guaranteed that an AggregateException always has an InnerException even if there are more than one. Or is there a case where I should fall back to .Flatten().First() ?
In some TPL docs, I see a reference to an Unwrap() method on AggregateException (not sure if it was an extension or something in a beta release).
As a placeholder, I'm doing:
void Call( )
{
try
{
CallAsync().Wait();
}
catch ( AggregateException ex )
{
var translated = ex.InnerException ?? ex.Flatten().InnerExceptions.First();
if ( translated == null )
throw;
throw translated; }
}
Task CallAsync(){ ...
There's no "clean" way to do this that I know of. You can't use throw someInnerException; because you'll lose the stack wherever the exception originated in the the async workflow and if you just use throw; you're obviously going to propagate the AggregateException. What you would have to do for the synchronous method is have some kind of "wrapper" exception that you can stuff the first exception of the AggregateException into and then throw that consistently from the synchronous version of the method.
void Call()
{
try
{
CallAsync().Wait();
}
catch (AggregateException ex)
{
throw new MyConsistentWrapperException("An exception occurred while executing my workflow. Check the inner exception for more details.", ex.Flatten().InnerExceptions.First());
}
}
FWIW, they've solved this in 4.5 with the new ExceptionDispatchInfo class which will help you marshal exceptions across threads without whacking the stack. Then you could write the synchronous version like this:
void Call()
{
try
{
CallAsync().Wait();
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.Flatten().InnerExceptions.First()).Throw();
}
}

Resources