-6

I'm trying to figure it out. I have this line of code:

MqttClient Client = new MqttClient(Broker, ClientId, Persistence);

But shows an "Unhandled exception" error. So I fixed it by enclosing it with a try/catch.

 try {
        MqttClient Client = new MqttClient(Broker, ClientId, Persistence);
    } catch (MqttException e) {
        e.printStackTrace();
    }

It actually works but can't understand why the need of this. Thanks in advance.

elwholer
  • 99
  • 1
  • 7
  • 6
    as per javadocs *Throws: java.lang.IllegalArgumentException - if the URI does not start with "tcp://", "ssl://" or "local://". java.lang.IllegalArgumentException - if the clientId is null or is greater than 65535 characters in length MqttException - if any other problem was encountered* – Scary Wombat Jan 20 '17 at 05:26

2 Answers2

3

The instance doesn't need to be surrounded by try/catch, but the constructor invocation does, or else needs to be within a method that is declared to throw that exception.

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

As hinted by some answers. I checked the class definition where are the following constructors:

public MqttClient(String serverURI, String clientId) throws MqttException {
    this(serverURI,clientId, new MqttDefaultFilePersistence());
}

public MqttClient(String serverURI, String clientId, MqttClientPersistence persistence) throws MqttException {
    aClient = new MqttAsyncClient(serverURI, clientId, persistence);
}

Both throw MqttException which is another class that extends Exception. Thank you so much.

elwholer
  • 99
  • 1
  • 7