Okan
Okan

Reputation: 1389

Try/catch block inside method

I have a class and I have a method inside this class.

Method:

public void login(String username,String password) throws XMPPException, SmackException, IOException {
    ConnectionConfiguration configuration=new ConnectionConfiguration("", 5222,"localhost");
    configuration.setSecurityMode(SecurityMode.disabled);
    connection=new XMPPTCPConnection(configuration);
    try {
        connection.connect();
        connection.login(username,password);
        ChatManager chatmanager = ChatManager.getInstanceFor(connection);
        chatmanager.addChatListener(new ChatManagerListener() {
            public void chatCreated(final Chat chat, final boolean createdLocally) {
                chat.addMessageListener(messageListener);
            }
        });
    }                       
    catch (XMPPException | SmackException | IOException e) {
        e.printStackTrace();
    }
}

Xmpp requires try/catch block.I defined try/catch inside method.But when I try to use this method in main class I am getting compiler error :

Unhandled exception type IOException

I am using like this:

SmackClass smack=new SmackClass();
smack.login("asdad","asdasd");

How can I resolve this problem ?

Upvotes: 1

Views: 2728

Answers (3)

chrana
chrana

Reputation: 209

Two possible solution

  1. Get rid of throws exception from the method
  2. Get rid of try and catch inside the method and use it in main like below:

:

 public static void main(string[] args){
try {
SmackClass smack=new SmackClass();
smack.login("asdad","asdasd");
}
catch (XMPPException | SmackException | IOException e) {
        e.printStackTrace();
    }
}

You are not handling the exception since your method can throw it

Upvotes: 0

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27476

Your method shouldn't declare throws XMPPException, SmackException, IOException, if you already handled it inside the login method.

Upvotes: 1

peter.petrov
peter.petrov

Reputation: 39457

XMPPException, SmackException, IOException

Remove these from the throws clause of the login method.

They cause the compile-time error in the main class.

In general, don't declare to throw those exceptions
which you already handle in the method itself.

Upvotes: 1

Related Questions