• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can a static final constant throw an exception?  RSS feed

 
John Boyes
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got a class constant which I've declared as private, final and static.
If I want the constructor for the class to throw an exception, is this possible? If I try to declare that the constructor throws an exception I'm told that the class constant must catch or throw that exception, which unless I'm mistaken it is unable to do as it is a private constant.
The only option I can think of is to throw a RuntimeException, as this would allow me to avoid declaring the Exception. This isn't ideal however.
Grateful for any replies,
John
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi John,
Welcome to Java Ranch!
You can do it, but you have to use a peculiar creature called a "static initialization block," and you have to get the initializer value all set before you try to assign it to the variable. Here's an example:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!