javatwitter4j

unreported exception twitter4j.TwitterException; must be caught or declared to be thrown


I have a code it provides that get twitter timeline i am trying to build a program but i see this error in intellij Idea:

java: unreported exception twitter4j.TwitterException; must be caught or declared to be thrown

but there is no error in eclipse ide

my code:

    @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());
    }
}

}


 

Solution

  • You need to handle the TwitterException that the code of the initializer block can throw, by wrapping it within a try-catch. Adding throws TwitterException in the main method will not solve the problem, because the exception is not thrown within the main method.

    {
        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
        }
    }
    

    if this is a console application, you can change the code to use a CommandLineRunner (see https://www.baeldung.com/spring-boot-console-app).