0

I apologize for the trivial nature of the following question, but I couldn't find an answer after a few minutes of Google searching.

I have a Java object that acts as the front-end to a developer SDK. This object is called DataCollectionManager. Like most, if not all, Android Manager objects (CameraManager, LocationManager, etc.), the DataCollectionManager manages the connection to a service running on the device.

When a client using the SDK creates a DataCollectionManager object, the constructor will bind to the DataCollectionService running on the device. The client provides a listener interface to the constructor that will be called back when the service connection has been established. Once this listener has been notified, the client knows it's okay to make API calls on the DataCollectionManager.

However, it is possible that a client will attempt to make an API call prior to the establishment of the service connection. In this case, I've got a block of code that looks like this at the top of each method:

if (!mServiceBound) {
   // do something
}

I'd like to throw an exception if the service is not bound, but I'm not sure which one.

Which exception should I throw? I'd like to throw a checked exception so the client code doesn't crash. Is there a preexisting exception that fits well in this case, or should I just define my own?

bstar55
  • 3,542
  • 3
  • 20
  • 24
  • If you didn't want it to be checked I'd suggest `IllegalStateException` but in this case, defining your own sounds best as it's a class of your own design. It forces developers to think about their code. – Dave Morrissey Jun 09 '14 at 17:22
  • @DaveMorrissey Hmmm, you're probably right. In this case, the client code would technically be incorrect if they are calling these APIs before they've received the service connection callback. I think I will use the IllegalStateException. I just looked at the documentation on that and it looks like it's used specifically for purposes such as this. If you'd like to formulate your comment into an answer below, I'll gladly give it the checkmark. – bstar55 Jun 09 '14 at 17:33

1 Answers1

0

I know of no such exception that you are looking for, so I suggest you create your own exception.

If you are lazy, you could just throw an "Exception" and put some text in it (e.g. throw new Exception("Service not bound!");). Obviously I don't recommend that, but if you dont want to take much time over something then it should work for mow.

To learn how to create your own exceptions, I suggest you have a look at How to create custom exceptions in Java?.

Community
  • 1
  • 1
Joehot200
  • 1,070
  • 15
  • 44