• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception in static block..

 
Abhineet Kapil
Ranch Hand
Posts: 52
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen if an exception occurs in a static block///

class A{

static
{

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

pvsm(){

sysout("Now i am in main");

}

}

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

Please give explaination..
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happened when you ran it ??

Also, please read this ShowSomeEffort

Using psvm is not cool ;-)
 
Sona Patel
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
at test.<clinit>(test.java:9)
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.

Regards
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic