How do I avoid errors when acessing base color space on a PDF element?

Q: I am getting an error when calling getFillColorSpace on element:

if (element.isFilled()) {
...
if (gs.getFillColorSpace() == ColorSpace.e_pattern) {
                colorSpace =
gs.getFillColorSpace().getBaseColorSpace();
}
}

Calling the getBaseColorSpace on a colorspace.e_pattern, it crashes
the application.
What am I doing wrong? I develop in JAVA.
------------------------------
A: You need to make sure that base color space exists and is valid.
For example:

if (gs.getFillColorSpace() == ColorSpace.e_pattern) {
     colorSpace = gs.getFillColorSpace();
    if (IsCSOk(colorSpace)) {
       ColorSpace baseCS = gs.getFillColorSpace();
         if (IsCSOk(baseCS)) {
            …
         }
    }
}

...

bool IsCSOk (ColorSpace cs ) {
  return cs!=null && cs.getSDFObj()!=null;
}