0

In my method below, I use a method in the net.sf.extJWNL package in the callback of the .anyMatch() method of Stream<Object>. However, the method I am using throws a JWNLException. Instead of the current try-catch block, I would like to use the throws keyword for the JWNLException.

Dictionary d = Dictionary.getDefaultResourceInstance();
List<POS> POSList =
     new ArrayList<POS>(EnumSet.allOf(POS.class));
boolean isWord = POSList.stream().anyMatch(c -> {
    try {
        return d.getIndexWord(c, word) != null;
    } catch (JWNLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return true;
    }
});

Also, I can't move this to a separate method because I need local variables from this method - d and word (parameter)

Marvin
  • 853
  • 2
  • 14
  • 38
  • `throws` is only used in method signatures. You probably want to move the body of your lambda to a private method, but you would not want to use `throws` on that method’s declaration, as that would defeat the point by forcing your lambda to retain the try/catch blocks. (Also, you don’t need an ArrayList; an EnumSet has a `stream()` method of its own, as do all Collections.) – VGR Aug 28 '19 at 20:55
  • Are you saying I can just remove line 2 completely and replace POSList.stream() with POS.stream()? This returns an error – Marvin Aug 28 '19 at 20:59
  • 1
    I’m saying you can write `Collection POSList = EnumSet.allOf(POS.class);`. – VGR Aug 28 '19 at 21:03
  • You should, however, follow the Java Naming Conventions: variable names should be written in camelCase. – MC Emperor Aug 28 '19 at 21:10
  • Well I do, but I am referring the enum POS here – Marvin Aug 28 '19 at 21:12
  • @MCEmperor the Java naming conventions allow this becuase POS is written as capital letters originally – Marvin Sep 08 '19 at 02:14
  • 1
    @Marvin **No, they don't.** They explicitly say that variable names always start with lowercase, and they do not mention the original writing at all. The generally accepted way to handle this is to treat acronyms as if they were normal words. `XMLHTTPParser` becomes `XmlHttpParser` and `POS` becomes `Pos` (see *Effective Java*). For variable names, the first letter is then converted to lowercase: e.g. `xmlHttpParser` and `pos`. – MC Emperor Sep 08 '19 at 09:38
  • Oh my bad. I was looking at a class name where you keep acronyms the same. – Marvin Sep 08 '19 at 14:24
  • https://stackoverflow.com/questions/2236807/java-naming-convention-with-acronyms – Marvin Sep 08 '19 at 14:25

1 Answers1

1

You may need to create a wrapper around the lambda expression, which will handle the exceptions which is being thrown from the piece of code.

Please refer to the link below

https://www.baeldung.com/java-lambda-exceptions

halfer
  • 19,824
  • 17
  • 99
  • 186
MRTJ
  • 141
  • 7