2

This piece of code shows exception:

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Ankit2.main(Ankit2.java:6)

Why and how its happening? Without using try and catch block?

class ankit1    
{
public static void main(String args[])    
 {
        float a=20,b=120,c=50,sum;    
        sum=(a+b+c)/0;    
        System.out.println("The average of three number is:"+sum);    
    }      

 }  
Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
Ankit
  • 255
  • 2
  • 7
  • 1
    When an Exception *terminates a thread* (that is, is not "catch"ed and suppressed) the JVM will print the Exception and stack-trace to the console, as seen. (Since this was the only foreground thread it also terminates the JVM instance.) Of course, the `println` line was *never executed* because of the Exception .. so yes, the JVM "handles" the Exception, but usually not in the desired manner. –  Aug 27 '12 at 06:34

2 Answers2

7

That is a RuntimeException.

You do not have to declare or catch those.

Any exception that your code does not catch (declared or not), will crash the running thread. In the case of the main thread that started the program, the JVM will print the stacktrace before exiting.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 5
    If crashing the program and printing a stacktrace is everything you want to do in case of an exception, then, yes, JVM is doing everything. But usually, you want to handle them in some other way (more gracefully). – Thilo Aug 27 '12 at 06:06
4

Operations like dividing by zero throw an unchecked exception. This is why your code compiled just fine without a try/catch block. That does not mean that no exception will be thrown at runtime. Look up the difference between checked and unchecked exceptions.

Ambar
  • 132
  • 1
  • 2