ArithmeticException

Examples of Exceptions

ArithmeticException

🙋 Need help? Ask an expert now!

Now let's examine the "ArithmeticException" that you have experienced before when we tried to divide an integer by zero. Anything that a calculator could not process would throw this type of exception. Please see the example below.

ArithmeticExceptionExample.java
package exlcode;

public class ArithmeticExceptionExample {

  public static void main(String[] args) {
    try {
      // ArithmeticException will be thrown because
      // a number cannot be divided by 0
      int exampleVariableOne = 500/0;
       System.out.println("You are not dividing a number by 0");
    } catch (ArithmeticException e) {
      System.out.println("Arithmetic Exception: cannot divide by 0");
    }
  }
}

In the scenario above, we divide by zero, which is why the "ArithmeticException" is thrown. Play around with the number you are dividing by to get the error to stop. As you can see, these errors are easily avoidable if you pay extreme attention to detail and ensure all of your expressions are mathematically correct when you code. In fact, when dealing with mathematical expressions, a logic error causes a larger problem because you will not receive an exception for it. This means you would have to sift through the code and dig up the mistake in order to resolve it. Always be very careful when writing calculations to ensure the intended result.

Edit Me on GitHub!

Application Question

Which of the following throws an ArithmeticException?