0

I need to do something like this:

while(prot.getProcessedTranscriptPositionFromAA(start) == null) start++;

But because prot throws NullPointerException I cannot loop like this. How can I create a loop that catches the NullPointerException, increments start, and executes getProcessedTranscriptPositionFromAA again ,and so on, until getProcessedTranscriptPositionFromAA will not throw NullPointerException ("it's ok" that the loop have the possibility to be infinite).

I never used goto and I don't even know how to use is, but will something like this will work somehow?:

        *here*
        try{
            prot.getProcessedTranscriptPositionFromAA(start);
        }
        catch (NullPointerException e){
            start++;
            goto *here*
        }
squeezy
  • 607
  • 1
  • 7
  • 15

4 Answers4

1

You don't need goto - there is no implemented goto in Java anyway. You can just put the try/catch in the loop. The loop can continue when the exception is caught, one thing has nothing to do with the other.

int start = 0;
boolean isNotNull = false;

while (!isNotNull) {
    try {
        prot.getProcessedTranscriptPositionFromAA(start);
        isNotNull = true;
    }
    catch (NullPointerException e) {
        start++;
    }
}

I have written this with the assumption that you have no say over how getProcessedTranscriptPositionFromAA() is implemented. However, if you do control this method, or know the person who does, make sure it does not throw a NullPointerException when passed an index to an empty location - that is not good API design. It should instead return something that indicates that the location is empty. There is a lot of lively disagreement over whether that something should be a null or a non-null object indicating emptiness; but either way, don't throw an exception.

Community
  • 1
  • 1
sparc_spread
  • 10,643
  • 11
  • 45
  • 59
0

You should prevent NullPointerException from being thrown in the first place. A NullPointerException usually indicates there's a bug in your code.

while (prot != null && prot.getProcessedTranscriptPositionFromAA(start) == null) start++;

If getProcessedTranscriptPositionFromAA itself may throw a NullPointerException, you should fix that method too.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Normally you write throws NullPointerException on same line of class name.For handling multiple NullPointerException in single class.

Gauri Shankar
  • 91
  • 3
  • 9
0

You could build a wrapper Method which catches the NPE for you.

Something like:

public static boolean getSomething(ProtClass prot){
    try{
        //do something
        return true;
    }catch(NullPointerException e){
        return false;
    }
}

and use this function in the while expression.

user
  • 735
  • 1
  • 6
  • 21