未报告的异常 twitter4j.TwitterException;必须被抓住或宣布被抛出
unreported exception twitter4j.TwitterException; must be caught or declared to be thrown
我有一个代码 provides 获取 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());
}
}
}
您需要处理初始化程序块的代码可能抛出的 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)。
我有一个代码 provides 获取 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());
}
}
}
您需要处理初始化程序块的代码可能抛出的 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)。