How to Avoid a Division by Zero Exception in Java

How to Avoid a Division by Zero Exception in Java thumbnail
Dividing by zero causes application crashes.

In any compiler language, a mathematical calculation where the divisor is zero results in a run-time error. The application will freeze or return an error to the user. For that reason, programmers should check the value of the divisor before performing the division calculation. This is accomplished using a condition statement called "if." The if statement is used to verify a condition before executing a command.

Instructions

    • 1

      Define your variables. In this example, a is divided by b, but only if b is not zero. To define variables, use the following code:
      int a = 1;
      int b = 0;
      int results = 0;

    • 2

      Set up the if statement. The following if statement code check the value of b to avoid the "divide by zero" error:
      if (b != 0)
      {
      }

    • 3

      Execute the math within the if statement. The enclosed statements are only executed if b is not zero, so you avoid the "divide by zero" error:
      if (b !=0)
      {
      results = a/b;
      }

Related Searches:

References

  • Photo Credit calculator04 image by Leslie Hoffmann from Fotolia.com

Comments

You May Also Like

  • How to Create a Custom Exception in Java

    Exceptions are a key tool in helping Java programs cope with the unexpected. As a developer, you can use the standard exception...

  • How to Catch an Exception in a Static Block in Java

    A static block of programming code in the Java programming language is used to execute a block of code one time during...

  • How to Enable Wireless Zero

    The Wireless Zero Configuration service is built into Windows XP and selects a wireless network dynamically to connect to based on your...

  • Changing Percentages to Decimals

    Percentages can be turned into decimals by turning the percentage into a fraction, dividing the top number by the bottom number and...

  • Array Index Out of Bounds Exception in Java

    Java programs use a variety of collection structures for storing and processing data. The array is one of the most common storage...

  • How to Perform a Bit Shift in Java

    The Java programming language allows you to perform bit shift and bitwise operations on the binary numbers that underlie the various data...

  • How to Solve Zero Exponents

    Learning to solve zero exponents is essential for any person that deals with math. Solve zero exponents with helpful instruction from a...

  • What Is Net Zero?

    NetZero is an Internet Service Provider (ISP) that began during the 1990s. NetZero was one of the few Internet-based companies to benefit...

Related Ads

Featured