【问题标题】:error unreported exception ClassNotFoundException; must be caught or declared to be thrown错误未报告的异常 ClassNotFoundException;必须被抓住或宣布被抛出
【发布时间】:2016-11-25 13:02:19
【问题描述】:

我使用的是雪球词干分析器,可以在这里找到http://snowball.tartarus.org/

我正在使用这个论坛问题为我自己的项目使用词干算法

Is there a java implementation of Porter2 stemmer

我使用给定的类并使用之前回答的帖子中给出的代码

Class stemClass = Class.forName("org.tartarus.snowball.ext." + lang + "Stemmer");
stemmer = (SnowballProgram) stemClass.newInstance();
stemmer.setCurrent("your_word");
stemmer.stem();
String your_stemmed_word = stemmer.getCurrent();  

但是当我开始使用 try catch 语句时,我得到了这个错误

assmt1/invert3.java:339: error: incompatible types: try-with-resources not applicable to variable type
      try(  Class stemClass = Class.forName("org.tartarus.snowball.ext." +"english"+ "Stemmer");
                  ^
(Class cannot be converted to AutoCloseable)
assmt1/invert3.java:340: error: incompatible types: try-with-resources not applicable to variable type
        SnowballStemmer stemmer = (SnowballStemmer) stemClass.newInstance())
                        ^
(SnowballStemmer cannot be converted to AutoCloseable)
2 errors

真的不知道如何解决这个问题

【问题讨论】:

  • 标题中的错误消息不会出现在问题的任何地方。请修复它。

标签: java error-handling porter-stemmer


【解决方案1】:

只有实现AutoCloseable 的类才能在try-with-resources 语句声明中使用。

try-with-resources 语句是一个 try 语句,它声明一个 或更多资源。 资源是必须在之后关闭的对象 该程序已完成。 try-with-resources 语句 确保每个资源在语句结束时关闭。任何 实现java.lang.AutoCloseable 的对象,其中包括所有 实现java.io.Closeable的对象可以作为资源使用。

ClassSnowballStemmer 不是 AutoCloseable。将其放在 try 块中:

try {
    Class stemClass = Class.forName("org.tartarus.snowball.ext." +"english"+ "Stemmer");
    SnowballStemmer stemmer = (SnowballStemmer) stemClass.newInstance();
} catch(Exception e){
    //Do Something
} finally {
    //Do Something
}

【讨论】:

  • 我收到这两个错误error: unreported exception ClassNotFoundException; must be caught or declared to be thrown Class stemClass = Class.forName("org.tartarus.snowball.ext." +"english"+ "Stemmer"); ^ assmt1/invert3.java:343: error: unreported exception InstantiationException; must be caught or declared to be thrown SnowballStemmer stemmer = (SnowballStemmer) stemClass.newInstance(); ^ 2 errors
  • 添加了 catch 块
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多