2

Sample Code:1

public class ClassTest     {
    public static void main(String[] args)  {
        throw  new java.lang.ArithmeticException(); 
    }
}

----No compilation Error for above code, Compiler is not asking to handle the Exception

Sample Code:2

public class ClassTest     {
    public static void main(String[] args)  {
        throw new java.lang.Exception();    
    }
}

--Compiler wants to handle Exception using try-catch or throws.

can anyone explain this behavior of compiler.I think it is because we need to specifically mention the XYZException class(other than Exception class).

trincot
  • 317,000
  • 35
  • 244
  • 286
Ajit Bisht
  • 39
  • 5
  • http://stackoverflow.com/questions/2190161/difference-between-java-lang-runtimeexception-and-java-lang-exception – MK. Jun 01 '16 at 19:50

2 Answers2

4

ArithmeticException is a RuntimeException and is not checked by the compiler. Exception is checked and will therefore prevent compilation if the rules are violated, such as not handling the method that throws the Exception.

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
0

In the Sample code 1, the exception we have is Arithmetic Exception which is Run time Exception . As we already know the Run time Exception implicitly propagates without using throws keyword at method signature, instead of handling it in the same method.

In the Sample code 2, the exception we have is Checked Exception which should be either handled by using try catch or by using throws keyword can be propagated. But throws keyword at method signature is missing , which results in compile time error.

Aditya
  • 43
  • 9