Can a static block throw exception?


Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.

Advertisements

7 thoughts on “Can a static block throw exception?

  1. Hello!
    Very Interesting post! Thank you for such interesting resource!
    PS: Sorry for my bad english, I’v just started to learn this language 😉
    See you!
    Your, Raiul Baztepo

  2. Hey i tried to throw an exception from static block but got a compilation error “Initializer does not complete normally”
    Here is the code snippet

    static {
    throw new RuntimeException(“This is an exception”);
    }

    1. У меня Windows XP SP2 x32, Java установил, запускаю minecraft v.1.4.3 (самая свежая), а у меня вылазит окно и там написано Could not cterae the java virtual machine ! Не знаю почему, переустанавливал Minecraft, а толку нет! Помогите!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s