0101011
0101011

Reputation: 329

Throw exception in class declaration

I am trying to throw an exception in the declaration of a class. Something like this:

class myClass throws A_Dangerous_Exception implements Something_to_Implement {

...

}

Any suggestions?

Upvotes: 1

Views: 6447

Answers (2)

Reimeus
Reimeus

Reputation: 159784

You can't. Exceptions can only be thrown from methods or constructors. You can do this:

class myClass implements Something_to_Implement {

   public myClass() throws A_Dangerous_Exception {
      ...
   }
}

Be careful to tidy up any resources such as FileOutputStream before throwing an exception from the constructor.

Read: Exceptions

Upvotes: 2

Bruno Reis
Bruno Reis

Reputation: 37822

You can't do that. You probably mean to throw an exception from the class' constructor:

class myClass implements Something_to_Implement {
  myClass() throws A_Dangerous_Exception {}
}

If you have multiple constructors, each one can have a different throws clause if you want:

class myClass implements Something_to_Implement {
  myClass() throws A_Dangerous_Exception {}
  myClass(int a) throws A_Dangerous_Exception, A_Not_So_Dangerous_Exception {}
}

Then, whenever you instantiate that class, you will have to deal with your exception(s), either by catching them or declaring them in the throws clause of the method where you instantiate your class:

void myMethod() {
  try {
    new myClass();
  } catch (A_Dangerous_Exception e) {}
}

or

void myMethod() throws A_Dangerous_Exception {
  new myClass();
}

Upvotes: 4

Related Questions