我有一个代码,它提供了获取twitter时间表,我正在尝试构建一个程序,但我在intellij Idea中看到了这个错误:
java: unreported exception twitter4j.TwitterException; must be caught or declared to be thrown但是在eclipse ide中没有错误。
我的代码:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws TwitterException {
SpringApplication.run(DemoApplication.class, args);
} {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.
setOAuthConsumerKey("XXX")
.
setOAuthConsumerSecret("XXX")
.
setOAuthAccessToken("XXX")
.
setOAuthAccessTokenSecret("XXX");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter4j.Twitter twitter = tf.getInstance();
List <Status> status = twitter.getHomeTimeline();
for(
Status st:status)
{
System.out.println(st.getUser().getName() + "----------" + st.getText());
}
}
}发布于 2021-08-02 13:37:19
您需要处理初始化程序块的代码可以抛出的TwitterException,方法是将它包装在一个try-catch中。在main方法中添加throws TwitterException不会解决问题,因为异常不会在main方法中抛出。
{
try {
ConfigurationBuilder cb = new ConfigurationBuilder();
List <Status> status = twitter.getHomeTimeline();
for(
Status st:status)
{
System.out.println(st.getUser().getName() + "----------" + st.getText());
}
} catch(TwitterException ex) {
... // handle exception
}
}如果这是一个控制台应用程序,您可以更改代码以使用CommandLineRunner (请参见https://www.baeldung.com/spring-boot-console-app)。
https://stackoverflow.com/questions/68622468
复制相似问题