It's not a secret anymore!
The moose likes Java in General and the fly likes Exception in static block.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Exception in static block.." Watch "Exception in static block.." New topic

Exception in static block..

Abhineet Kapil
Ranch Hand

Joined: Feb 08, 2010
Posts: 52

What will happen if an exception occurs in a static block///

class A{


sysout("static block started ");
int a = 0;
int b=500;
int c= 0;
sysout("static block finished");


sysout("Now i am in main");



What will be the output ?? ......

Please give explaination..
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
What happened when you ran it ??

Also, please read this ShowSomeEffort

Using psvm is not cool ;-)

JDBCSupport - An easy to use, light-weight JDBC framework -
Sona Patel
Ranch Hand

Joined: Mar 30, 2009
Posts: 75
Hi Abhineet,

I tried your code which works fine without any exception. Then i changed division statement in static block to c=b/a. This time it gave following output -

static block started
Caused by: java.lang.ArithmeticException: / by zero
at test.<clinit>(
Exception in thread "main"

Static block is executed before execution of Main method starts. Any exception E if not caught in static block then If the class of E is not Error or one of its subclasses, then a new instance of the class ExceptionInInitializerError is created, with E as the argument, and used. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead an OutOfMemoryError object in place of E is used.

I agree. Here's the link:
subject: Exception in static block..
It's not a secret anymore!