Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

static block

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What happens if a static blocks throws an exception. How do I handle it? I know the code below won't compile, but do we have an alternative, to make it work.
ex.
public ClassXYZ
{
static
{
throw new Exception();
}
}
 
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My 2 cents here, you can put the try - catch block there

public ClassXYZ
{
static
{
try { code may throw ExpectedEx}
catch (ExpectedEx e) { }

}
}
 
Shubh Bhat
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Isn't there any other way. Can't we do without try catch?
 
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's think about what might happen if a static initializer threw an exception.
The only way to propagate information about what exceptions might be raised is through the throws clause of a constructor or a method. A static initializer does not have a throws clause.
If a static initializer had a throws clause, the code that caused a class to be initialized would have to handle the exception.
The virtual machine must initialize a class on its first active use. An active use includes class instantiation, invoking a static method and using or assigning a static field.
Therefore, if a static initializer had a throws clause, every use and assigning of a static field would have to handle the exception.
Maybe that is why static initializers do not have a throws clause.
[ June 27, 2003: Message edited by: Marlene Miller ]
reply
    Bookmark Topic Watch Topic
  • New Topic