aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Enum Constructor - Exception and Accessibility Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Enum Constructor - Exception and Accessibility" Watch "Enum Constructor - Exception and Accessibility" New topic
Author

Enum Constructor - Exception and Accessibility

Chinmay Naik
Greenhorn

Joined: Jan 04, 2009
Posts: 2
I have following questions about Enums:

1) Can an enum constructor throw any checked exceptions?
I wrote the following code but I am getting compile time error saying unhandled exception of type Exception.

Can somebody please explain why? Is there any way, wherein we can write enum constructor that throws some checked exception?
=========================================================================================
2) Also, can somebody tell me why compiler does not allow me to declare enum constructor of any enum as public or protected. It says, only private is permitted. However, I could declare enum constructor with no modifier (i.e. with default scope). So why only default scope and private scope is allowed for enum constructors?
Alfred Swensen
Greenhorn

Joined: May 25, 2009
Posts: 10

Chinmay Naik wrote:
1) Can an enum constructor throw any checked exceptions?


AFAIK, no. To understand enums I try to think of them as pure syntactic suger, behind the scenes the java compiler could (at least theoretically) be transform them into a plain old java class before compiling them:



If you try to compile that, you see that you get exactly the same error message, but now you understand why the Exception is illegal:





2) Also, can somebody tell me why compiler does not allow me to declare enum constructor of any enum as public or protected. It says, only private is permitted.
However, I could declare enum constructor with no modifier (i.e. with default scope). So why only default scope and private scope is allowed for enum constructors?


public and protected are forbidden because then you would imply that you are planning to call the constructor from outside the class - as Enums may only consist
of compile time constants, this must be prohibited.

Regarding the "default" access level, I tend to use my above explanation that an enum is just a convenience representation and that the compiler will add an "private" implicitly before compiling it.

karthick chinnathambi
Ranch Hand

Joined: Jul 06, 2009
Posts: 196

this is to prevent you from calling enum-constructor explicitly......
you can't call an enum constructor explicitly


KARTHICK.C , SCJP6-93%
(Born to Win)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Enum Constructor - Exception and Accessibility