Does Java handle exception automatically without using a try and catchblock?

半城伤御伤魂 提交于 2019-12-12 21:24:00

问题


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);    
    }      

 }  

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12136880/does-java-handle-exception-automatically-without-using-a-try-and-catchblock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!