简体   繁体   中英

Exception in thread “main” java.lang.ArithmeticException: / by zero

I have two questions about Exceptions . Firstly, I got this message from my code...

Exception in thread "main" java.lang.ArithmeticException: / by zero

This error message means dividing by zero, such as by doing int a = 5 / 0;

A method can throw an Exception class instance, can't it? But this is an expression. Why can an expression throw an Exception class instance ?

My second question is about thread "main" . What is thread "main" ? Does "main" mean the static main method?

java.lang.ArithmeticException is a type of Exception that aims to better describe what the problem actually is. There's no point just creating an Exception , as it really could be caused by anything. By generating an ArithmeticException , the user can immediately know that the problem is something to do with a calculation. An Exception can be thrown by any piece of code, including in calculations such as your example.

Exception in thread "main" means that the exception is thrown by the main() method, which also happens to be the primary Thread that is running your code.

Method can throw exception class instance, isn't it?

Yes they can.

But this is statement. Why can statement throw exception class instance ?

Exception can occur anywhere. So even statements can throw exceptions. And in case you meant why can't statements throw exceptions,well they can. Here's an example:

if ((a/b) == 0) {
        throw new ArithmeticException();
    }

Second question is about thread "main". What is thread "main" ?

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins.

Its Arithmetic exception case: means something in logic which not exist in Mathematical arithmetic;

Check the condition of the "for loop" or any other logical functions.

An example is when somewhere you write something like: (n % i == 0) and give initialization i = 0 , now every one knows that number can not be divided by Zero. So, you may need to change the initialization to i = 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM