0

Let's say I have this if-else statement:

        if (isAdd()) {
            return addStatement();
        } else if (isChange()) {
            return chgStatement();
        } else if (isDelete()) {
            return delStatement();
        } else return null;

I want to wrap this in a try-catch statement, but I want to catch the null. How would I do this? I attempted:

    try{
        if (isAdd()) {
            return addStatement();
        } else if (isChange()) {
            return chgStatement();
        } else if (isDelete()) {
            return delStatement();
        } else return null;
    } catch(NullPointerException e){
        log.error("null!");
    }

    return null;

My problem is that I never want to hit the else return null, but I need to check else if(isDelete()) rather than just else return delStatement();

Mike Henke
  • 641
  • 2
  • 10
  • 24
  • For dealing with null pointer exceptions consider `Optional<>` . It was designed to be return type of methods that may return null value. – callOfCode Aug 05 '16 at 16:32
  • 1
    Never, **NEVER** catch a NPE. Instead do a simple null check in your if block. – Hovercraft Full Of Eels Aug 05 '16 at 16:33
  • which null are you trying to catch here? the 'return null' does NOT throw a NullPointerException, as you seem to be inplying – Drgabble Aug 05 '16 at 16:33
  • 1
    For your reading pleasure: [Google search on this site on catching a NPE](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+catch+a+nullpointerexception) – Hovercraft Full Of Eels Aug 05 '16 at 16:34
  • 2
    `return null` does not cause a NullPointer so nothing to catch here. It is quite unclear on what you want to do and why. – k5_ Aug 05 '16 at 16:35
  • I think the answer you want is to replace 'return null' with 'throw new UsefulExceptionHere' – Drgabble Aug 05 '16 at 16:38

0 Answers0