Division by zero error java

I have code to calculate the percentage difference between 2 numbers - (oldNum - newNum) / oldNum * 100; - where both of the numbers are doubles. I expected to have to add some sort of checking /

I have code to calculate the percentage difference between 2 numbers — (oldNum - newNum) / oldNum * 100; — where both of the numbers are doubles. I expected to have to add some sort of checking / exception handling in case oldNum is 0. However, when I did a test run with values of 0.0 for both oldNum and newNum, execution continued as if nothing had happened and no error was thrown. Running this code with ints would definitely cause an arithmetic division-by-zero exception. Why does Java ignore it when it comes to doubles?

Aziz Shaikh's user avatar

Aziz Shaikh

16.1k11 gold badges61 silver badges79 bronze badges

asked Mar 4, 2010 at 17:57

froadie's user avatar

3

Java’s float and double types, like pretty much any other language out there (and pretty much any hardware FP unit), implement the IEEE 754 standard for floating point math, which mandates division by zero to return a special «infinity» value. Throwing an exception would actually violate that standard.

Integer arithmetic (implemented as two’s complement representation by Java and most other languages and hardware) is different and has no special infinity or NaN values, thus throwing exceptions is a useful behaviour there.

answered Mar 4, 2010 at 18:16

Michael Borgwardt's user avatar

Michael BorgwardtMichael Borgwardt

340k77 gold badges477 silver badges713 bronze badges

2

The result of division by zero is, mathematically speaking, undefined, which can be expressed with a float/double (as NaN — not a number), it isn’t, however, wrong in any fundamental sense.

As an integer must hold a specific numerical value, an error must be thrown on division by zero when dealing with them.

RubioRic's user avatar

RubioRic

2,4474 gold badges28 silver badges35 bronze badges

answered Mar 4, 2010 at 17:58

Kris's user avatar

KrisKris

14.3k7 gold badges54 silver badges65 bronze badges

13

When divided by zero ( 0 or 0.00 )

  1. If you divide double by 0, JVM will show Infinity.

    public static void main(String [] args){ double a=10.00; System.out.println(a/0); }

    Console:
    Infinity

  2. If you divide int by 0, then JVM will throw Arithmetic Exception.

    public static void main(String [] args){
    int a=10;
    System.out.println(a/0);
    }

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

  3. But if we divide int by 0.0, then JVM will show Infinity:

    public static void main(String [] args){
    int a=10;
    System.out.println(a/0.0);
    }

    Console: Infinity

This is because JVM will automatically type cast int to double, so we get infinity instead of ArithmeticException.

answered Oct 1, 2017 at 10:59

Raman Gupta's user avatar

Raman GuptaRaman Gupta

1,53015 silver badges12 bronze badges

The way a double is stored is quite different to an int. See http://firstclassthoughts.co.uk/java/traps/java_double_traps.html for a more detailed explanation on how Java handles double calculations. You should also read up on Floating Point numbers, in particular the concept of Not a Number (NaN).

If you’re interested in learning more about floating point representation, I’d advise reading this document (Word format, sorry). It delves into the binary representation of numbers, which may be helpful to your understanding.

answered Mar 4, 2010 at 18:05

Mike's user avatar

MikeMike

2,4071 gold badge24 silver badges32 bronze badges

0

Though Java developers know about the double primitive type and Double class, while doing floating point arithmetic they don’t pay enough attention to Double.INFINITY, NaN, -0.0 and other rules that govern the arithmetic calculations involving them.

The simple answer to this question is that it will not throw ArithmeticException and return Double.INFINITY. Also, note that the comparison x == Double.NaN always evaluates to false, even if x itself is a NaN.

To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. This is very close to NULL in SQL.

It may helpful for you.

answered Feb 2, 2016 at 10:18

ziyapathan's user avatar

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Exceptions These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program.

    Handling Multiple exceptions: There are two methods to handle multiple exceptions in java.

    1. Using a Single try-catch block try statement allows you to define a block of code to be tested for errors, and we can give exception objects to the catch blow because this all the exceptions inherited by the Exception class.
    2. The second method is to create individual catch blocks for the different exception handler.

    Hierarchy of the exceptions:

    Divide by zero: This Program throw Arithmetic exception because of due any number divide by 0 is undefined in Mathematics. 

    Java

    import java.io.*;

    class GFG {

        public static void main(String[] args)

        {

            int a = 6;

            int b = 0;

            System.out.print(a / b);

        }

    }

    Output:

    divideByZeroError

    Handling of Divide by zero exception: Using try-Catch Block 

    Java

    import java.io.*;

    class GFG {

        public static void main(String[] args)

        {

            int a = 5;

            int b = 0;

            try {

                System.out.println(a / b);

            }

            catch (ArithmeticException e) {

                System.out.println(

                    "Divided by zero operation cannot possible");

            }

        }

    }

    Output:

    Divide by zero exception handle

    Multiple Exceptions (ArithmeticException and IndexoutOfBound Exception)

    1. Combination of two Exception using the | operator is allowed in Java.
    2. As soon as the first exception occurs it gets thrown at catch block.
    3. Check of expression is done by precedence compiler check rule from right to left of the expression.

    Java

    import java.io.*;

    class GFG {

        public static void main(String[] args)

        {

            try {

                int number[] = new int[10];

                number[10] = 30 / 0;

            }

            catch (ArithmeticException e) {

                System.out.println(

                    "Zero cannot divide any number");

            }

            catch (ArrayIndexOutOfBoundsException e) {

                System.out.println(

                    "Index out of size of the array");

            }

        }

    }

    Output:

    Explanation: Here combination of ArrayIndexOutOfBounds and Arithmetic exception occur, but only Arithmetic exception is thrown, Why?

    According to the precedence compiler check number[10]=30/0 from right to left. That’s why 30/0 to throw ArithmeticException object and the handler of this exception executes Zero cannot divide any number.

    Another Method of Multiple Exception: we can combine two Exception using the | operator and either one of them executes according to the exception occurs.

    Java

    import java.io.*;

    class GFG {

        public static void main(String[] args)

        {

            try {

                int number[] = new int[20];

                number[21] = 30 / 9;

            }

            catch (ArrayIndexOutOfBoundsException

                   | ArithmeticException e) {

                System.out.println(e.getMessage());

            }

        }

    }

    Output:

    1. Divide by Integer Zero Exception in Java
    2. Divide by Floating Point Zero Exception in Java

    Divide by Zero Exception in Java

    This article will demonstrate what happens in a Java program when dividing by zero. Dividing by zero is an undefined operation since it has no significance in regular arithmetic.

    While it is frequently connected with an error in programming, this is not necessarily the case. According to the Java division operation definition, we may look at a scenario of division by zero integers.

    Divide by Integer Zero Exception in Java

    Dividing a real integer by zero is a mathematical procedure that appears to be relatively easy yet lacks a clear and conclusive solution. Because any effort at definition leads to a contradiction, the outcome of this operation is technically deemed undefined.

    Because this is a specific example of the division operation, Java recognizes it as an exceptional circumstance and throws the ArithmeticException whenever it comes across it during runtime.

    public class dividebyzero {
        public static int divide(int f, int g) {
            int h = f / g;
            return h ;
        }
        public static void main(String... args) {
            int d = 8, r = 0;
            int e = divide(d, r);
            System.out.println(e);
        }
    }
    

    Output:

    Exception in thread "main" java.lang.ArithmeticException: / by zero
        at dividebyzero.divide(dividebyzero.java:3)
        at dividebyzero.main(dividebyzero.java:8)
    

    Resolve Divide by Integer Zero Exception in Java

    The right approach to handle division by zero is to ensure that the divisor variable is never 0.

    When the input cannot be controlled, and there is a potential of zero presenting itself in the equation, treat it as one of the expected choices and resolve it accordingly.

    This normally entails checking the divisor’s value before using it, as shown below:

    public class dividebyzero {
        public static int divide(int f, int g) {
            int h = f / g;
            return h ;
        }
        public static void main(String... args) {
            int d = 8, r = 0;
            if (r != 0) {
                int e = divide(d, r);
                System.out.println(e);
            } else {
                System.out.println("Invalid divisor: division by zero can't be processed)");
            }
        }
    }
    

    Output:

    Invalid divisor: division by zero can't be processed)
    

    Java includes a specialized exception named ArithmeticException to deal with unusual circumstances that emerge from computations.

    When dealing with exceptional instances like integer division by zero, being very precise and careful is the key to avoiding the ArithmeticException.

    Divide by Floating Point Zero Exception in Java

    Floating-point values, by the way, also have -0.0; thus, 1.0/ -0.0 is -Infinity. Integer arithmetic lacks any of these values and instead throws an exception.

    For example, unlike java.lang.ArithmeticException, the following case does not produce an exception when divided by zero. It expresses the infinite.

    int x = 0;
    double y = 3.2500;
    System.out.println((y/x));
    

    This is because you are working with floating-point numbers. Infinity is returned by division by zero, which is comparable to not a number or NaN.

    You must test tab[i] before using it if you wish to avoid this. Then, if necessary, you can throw your own exception.

    Java will not throw an exception whenever you divide by float zero. This will only notice a runtime bug when you divide by integer zero rather than double zero.

    If you divide Infinity by 0.0, the outcome is Infinity.

    0.0 is a double literal, and it is not regarded as absolute zero. There is no exception since the double variable is large enough to handle numbers representing approaching infinity.

    You can use the line of code shown below to check for all possible values that could result in a nonfinite number, such as NaN, 0.0, and -0.0.

    if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY){
        throw new ArithmeticException("Result is non finite");
    }
    

    You may also check for yourself and then throw an exception.

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];
            if (tab[i] == Double.POSITIVE_INFINITY ||tab[i] == Double.NEGATIVE_INFINITY)
            { throw new ArithmeticException(); }
        }
        } catch (ArithmeticException xy) {
            System.out.println("ArithmeticException occured!");
    }
    

    Содержание

    1. Java Program to Handle Divide By Zero and Multiple Exceptions
    2. Facing Issues On IT
    3. [Solved] java.lang.ArithmeticException: / by zero in JAVA
    4. How to fix Arithmetic Exception?
    5. How to Solve the Most Common Runtime Errors in Java
    6. Runtime Errors vs Compile-Time Errors
    7. Runtime Errors vs Logical Errors
    8. What Causes Runtime Errors in Java
    9. Runtime Error Examples
    10. Division by zero error
    11. Accessing an out of range value in an array
    12. How to Solve Runtime Errors
    13. Track, Analyze and Manage Errors With Rollbar
    14. Runtime Errors in Java [SOLVED]
    15. Fix the 5 Most Common Types of Runtime Errors in Java
    16. What is a Runtime Error in Java?
    17. Differences Between Compile Time Error and Runtime Error in Java
    18. Why Runtime Error Occurs in Java ?
    19. NUM02-J. Ensure that division and remainder operations do not result in divide-by-zero errors
    20. Noncompliant Code Example (Division)
    21. Compliant Solution (Division)
    22. Noncompliant Code Example (Remainder)
    23. Compliant Solution (Remainder)
    24. Risk Assessment

    Java Program to Handle Divide By Zero and Multiple Exceptions

    Exceptions These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program.

    Handling Multiple exceptions: There are two methods to handle multiple exceptions in java.

    1. Using a Single try-catch block try statement allows you to define a block of code to be tested for errors, and we can give exception objects to the catch blow because this all the exceptions inherited by the Exception class.
    2. The second method is to create individual catch blocks for the different exception handler.

    Hierarchy of the exceptions:

    Divide by zero: This Program throw Arithmetic exception because of due any number divide by 0 is undefined in Mathematics.

    Output:

    Handling of Divide by zero exception: Using try-Catch Block

    Output:

    Multiple Exceptions (ArithmeticException and IndexoutOfBound Exception)

    1. Combination of two Exception using the | operator is allowed in Java.
    2. As soon as the first exception occurs it gets thrown at catch block.
    3. Check of expression is done by precedence compiler check rule from right to left of the expression.

    Output:

    Explanation: Here combination of ArrayIndexOutOfBounds and Arithmetic exception occur, but only Arithmetic exception is thrown, Why?

    According to the precedence compiler check number[10]=30/0 from right to left. That’s why 30/0 to throw ArithmeticException object and the handler of this exception executes Zero cannot divide any number.

    Another Method of Multiple Exception: we can combine two Exception using the | operator and either one of them executes according to the exception occurs.

    Источник

    Facing Issues On IT

    [Solved] java.lang.ArithmeticException: / by zero in JAVA

    java.lang.ArithmeticException is Unchecked exception and sub class of java.lang.RuntimeException. It’s thrown when an exceptional condition occurred in Arithmetic Operations. It can also occurred by virtual machine as if suppression were disabled and /or the stack trace was not writable.

    Constructors:

    • ArithmeticException() : Constructs an ArithmeticException with no detail message.
    • ArithmeticException(String s) : Constructs an ArithmeticException with the specified detail message.

    Output:

    How to fix Arithmetic Exception?

    In above example:

    Y/X or K/X result ArithmeticException

    What happens here is that since both the dividend and the divisor are int , the operation is an integer division, whose result is rounded to an int . Remember that an int can only contain whole number (of limited range, some 4 billion numbers approximately) That’ s why throwing Arithmatic Exception. same case for long value.

    Z/X or L/X result special value Infinity

    Here float (L) or double (X) precision value divide by zero store in float and double value that why result is special value Infinity.

    Источник

    How to Solve the Most Common Runtime Errors in Java

    Table of Contents

    A runtime error in Java is an application error that occurs during the execution of a program. A runtime error occurs when a program is syntactically correct but contains an issue that is only detected during program execution. These issues cannot be caught at compile-time by the Java compiler and are only detected by the Java Virtual Machine (JVM) when the application is running.

    Runtime errors are a category of exception that contains several more specific error types. Some of the most common types of runtime errors are:

    • IO errors
    • Division by zero errors
    • Out of range errors
    • Undefined object errors

    Runtime Errors vs Compile-Time Errors

    Compile-time errors occur when there are syntactical issues present in application code, for example, missing semicolons or parentheses, misspelled keywords or usage of undeclared variables.

    These syntax errors are detected by the Java compiler at compile-time and an error message is displayed on the screen. The compiler prevents the code from being executed until the error is fixed. Therefore, these errors must be addressed by debugging before the program can be successfully run.

    On the other hand, runtime errors occur during program execution (the interpretation phase), after compilation has taken place. Any code that throws a runtime error is therefore syntactically correct.

    Runtime Errors vs Logical Errors

    A runtime error could potentially be a legitimate issue in code, for example, incorrectly formatted input data or lack of resources (e.g. insufficient memory or disk space). When a runtime error occurs in Java, the compiler specifies the lines of code where the error is encountered. This information can be used to trace back where the problem originated.

    On the other hand, a logical error is always the symptom of a bug in application code leading to incorrect output e.g. subtracting two variables instead of adding them. In case of a logical error, the program operates incorrectly but does not terminate abnormally. Each statement may need to be checked to identify a logical error, which makes it generally harder to debug than a runtime error.

    What Causes Runtime Errors in Java

    The most common causes of runtime errors in Java are:

    • Dividing a number by zero.
    • Accessing an element in an array that is out of range.
    • Attempting to store an incompatible type value to a collection.
    • Passing an invalid argument to a method.
    • Attempting to convert an invalid string to a number.
    • Insufficient space in memory for thread data.

    When any such errors are encountered, the Java compiler generates an error message and terminates the program abnormally. Runtime errors don’t need to be explicitly caught and handled in code. However, it may be useful to catch them and continue program execution.

    To handle a runtime error, the code can be placed within a try-catch block and the error can be caught inside the catch block.

    Runtime Error Examples

    Division by zero error

    Here is an example of a java.lang.ArithmeticException , a type of runtime exception, thrown due to division by zero:

    In this example, an integer a is attempted to be divided by another integer b , whose value is zero, leading to a java.lang.ArithmeticException :

    Accessing an out of range value in an array

    Here is an example of a java.lang.ArrayIndexOutOfBoundsException thrown due to an attempt to access an element in an array that is out of bounds:

    In this example, an array is initialized with 5 elements. An element at position 5 is later attempted to be accessed in the array, which does not exist, leading to a java.lang.ArrayIndexOutOfBoundsException runtime error:

    How to Solve Runtime Errors

    Runtime errors can be handled in Java using try-catch blocks with the following steps:

    • Surround the statements that can throw a runtime error in try-catch blocks.
    • Catch the error.
    • Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.

    To illustrate this, the code in the earlier ArithmeticException example can be updated with the above steps:

    Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

    Runtime errors can be avoided where possible by paying attention to detail and making sure all statements in code are mathematically and logically correct.

    Track, Analyze and Manage Errors With Rollbar

    ![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)

    Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing errors easier than ever. Try it today.

    Источник

    Runtime Errors in Java [SOLVED]

    While working with the programming languages like executing a software program, there are many instances that we run into issues due to the run time errors or compilation errors. All these errors occur when the application is running. You might come across an instance where the application acts differently in a negative way to the requirements, then it means that a runtime error took place.

    As it is one of the most common type of error that occurs during a software executive, let us get a deep idea on how to fix common types of runtime errors in Java and also the steps to be taken to resolve them on a timely basis.

    Fix the 5 Most Common Types of Runtime Errors in Java

    What is a Runtime Error in Java?

    A runtime error in Java is referred to as an application error that comes up during the execution process of the program. This runtime error usually takes place when the syntax is corrected as expected while the issue lies during the program execution. All these errors can be detected by JVM – Java Virtual Machine and cannot be identified during the compilation time. Java is one of the most sought-after programming languages for the hiring managers across the world. So become an expert in Java through our Java Training and grab the best job opportunity.

    Now, In this post, Let us discuss the top runtime errors in Java.

    1. Division by zero errors
    2. IO errors
    3. Out of range errors
    4. Undefined object errors

    Differences Between Compile Time Error and Runtime Error in Java

    Compile time errors are those errors in which the syntax would be incorrect in the application code. An example would be like missing semicolons, parenthesis, incorrect keywords, usage of undeclared variables, etc.

    The Java compiler is capable of detecting the syntax errors during the compile time and the error message will be appearing on the screen. The compiler is also capable of preventing the code from the execution unless and until the error is resolved. Therefore it is important that these errors are addressed by making the necessary changes before the program is successfully executed.

    The runtime errors occur during the program execution after the compilation has completed. Any program that is throwing a runtime error means that there are no issues with Syntax in the program.

    Why Runtime Error Occurs in Java ?

    Below listed are the most common types of runtime errors that occur in Java.

    1. Accessing an element that is out of range in an array
    2. Dividing a number with 0
    3. Less space or insufficient space memory
    4. Conversion of an invalid string into a number
    5. Attempting to store an incompatible value to a collection

    When you come across such an address, you need to know that the Java compiler will be generating an error message and the program gets terminated abnormally. Runtime errors do not require to be caught explicitly. It is useful if you catch the runtime errors and resolve them to complete the program execution.

    Let us review a few of the most common runtime errors in Java programming with examples to gain a deeper understanding.

    Источник

    NUM02-J. Ensure that division and remainder operations do not result in divide-by-zero errors

    Division and remainder operations performed on integers are susceptible to divide-by-zero errors. Consequently, the divisor in a division or remainder operation on integer types must be checked for zero prior to the operation. Division and remainder operations performed on floating-point numbers are not subject to this rule.

    Noncompliant Code Example (Division)

    The result of the / operator is the quotient from the division of the first arithmetic operand by the second arithmetic operand. Division operations are susceptible to divide-by-zero errors. Overflow can also occur during two’s-complement signed integer division when the dividend is equal to the minimum (negative) value for the signed integer type and the divisor is equal to −1 (see NUM00-J. Detect or prevent integer overflow for more information). This noncompliant code example can result in a divide-by-zero error during the division of the signed operands num1 and num2 :

    Compliant Solution (Division)

    This compliant solution tests the divisor to guarantee there is no possibility of divide-by-zero errors:

    Noncompliant Code Example (Remainder)

    The % operator provides the remainder when two operands of integer type are divided. This noncompliant code example can result in a divide-by-zero error during the remainder operation on the signed operands num1 and num2 :

    Compliant Solution (Remainder)

    This compliant solution tests the divisor to guarantee there is no possibility of a divide-by-zero error:

    Risk Assessment

    A division or remainder by zero can result in abnormal program termination and denial-of-service (DoS).

    Источник

    While working with the programming languages like executing a software program, there are many instances that we run into issues due to the run time errors or compilation errors. All these errors occur when the application is running. You might come across an instance where the application acts differently in a negative way to the requirements, then it means that a runtime error took place.

    As it is one of the most common type of error that occurs during a software executive, let us get a deep idea on how to fix common types of runtime errors in Java and also the steps to be taken to resolve them on a timely basis.

    Contents

    • 1 Fix the 5 Most Common Types of Runtime Errors in Java
      • 1.1  What is a Runtime Error in Java?
      • 1.2 Differences Between Compile Time Error and Runtime Error in Java
      • 1.3 Why Runtime Error Occurs in Java ?
      • 1.4 1. Accessing Out of Range Value in an Array
      • 1.5 2. Division by Zero Error
      • 1.6 3. Less Space or Insufficient Space Memory Error
      • 1.7 4. Conversion of an Invalid string into a Number
      • 1.8 5. Attempting to Store an Incompatible Value to a Collection
      • 1.9 How to solve Runtime Rrror in Java Programming?

    Fix the 5 Most Common Types of Runtime Errors in Java

     What is a Runtime Error in Java?

    A runtime error in Java is referred to as an application error that comes up during the execution process of the program. This runtime error usually takes place when the syntax is corrected as expected while the issue lies during the program execution. All these errors can be detected by JVM – Java Virtual Machine and cannot be identified during the compilation time. Java is one of the most sought-after programming languages for the hiring managers across the world. So become an expert in Java through our Java Training and grab the best job opportunity.

    Now, In this post, Let us discuss the top runtime errors in Java.

    1. Division by zero errors
    2.  IO errors
    3. Out of range errors
    4. Undefined object errors

    Differences Between Compile Time Error and Runtime Error in Java

    Compile time errors are those errors in which the syntax would be incorrect in the application code. An example would be like missing semicolons, parenthesis, incorrect keywords, usage of undeclared variables, etc. 

    The Java compiler is capable of detecting the syntax errors during the compile time and the error message will be appearing on the screen. The compiler is also capable of preventing the code from the execution unless and until the error is resolved. Therefore it is important that these errors are addressed by making the necessary changes before the program is successfully executed.

    The runtime errors occur during the program execution after the compilation has completed. Any program that is throwing a runtime error means that there are no issues with Syntax in the program.

    Why Runtime Error Occurs in Java ?

     Below listed are the most common types of runtime errors that occur in Java.

    1. Accessing an element that is out of range in an array
    2. Dividing a number with 0
    3. Less space or insufficient space memory
    4. Conversion of an invalid string into a number
    5. Attempting to store an incompatible value to a collection

    When you come across such an address, you need to know that the Java compiler will be generating an error message and the program gets terminated abnormally. Runtime errors do not require to be caught explicitly. It is useful if you catch the runtime errors and resolve them to complete the program execution. 

    Let us review a few of the most common runtime errors in Java programming with examples to gain a deeper understanding.

    1. Accessing Out of Range Value in an Array

    public class ValueOutOfRangeErrorExample {

    public static void main(String[] args) {

         int k[] = new int[8];

            System.out.println(«8th element in array: « + k[8]);

    }

    }

    In the above example, the array is initialized with 8 elements. with the above code, An element at position number 8 is trying to get access and does not exist at all, leading to the Exception java.lang.ArrayIndexOutOfBoundsException:

    Error :

    Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException:

    Index 8 out of bounds for length 8  

    at ValueOutOfRangeErrorExample.main(ValueOutOfRangeErrorExample.java:4)

    2. Division by Zero Error

    Below is an example of java.lang.ArithmeticException which occurs when the user is trying to code in such a way that they perform the division by zero.

    public class ArithmeticExceptionExample {

    public static void main(String[] args) {

           int num1 = 10, num2 = 0;

              System.out.println(«Result: «+ num1/num2);

    }

    }

    In the above code, the integer num1 is getting to be divided by num2 which has a value of zero, which is leading to the exception called java.lang.ArithmeticException

    Below is the Error Thrown :

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

    at ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:4)

    3. Less Space or Insufficient Space Memory Error

    Below is an example of java.lang.OutOfMemoryError, which occurs when the user is trying to initialize an Integer array with a very large size, and due to the Java heap being insufficient to allocate this memory space, it throws an Error  java.lang.OutOfMemoryError: Java heap space

    public class OutOfMemory {

    public static void main(String[] args) {

    Integer[] myArray = new Integer[1000*1000*1000];

    }

    }

    Error :

    Exception in thread «main» java.lang.OutOfMemoryError: Java heap space

    at OutOfMemory.main(OutOfMemory.java:5)

    4. Conversion of an Invalid string into a Number

    Below is an example of java.lang.NumberFormatException, occurs when the user is trying to convert an alphanumeric string to an integer which leads to java.lang.NumberFormatException

    public class NumberFormatException {

    public static void main(String[] args) {

    int a;

    a= Integer.parseInt(«12Mehtab»);

    System.out.println(a);

    }

    }

    Error :

    Exception in thread «main» java.lang.NumberFormatException: For input string: «12Mehtab»

    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

    at java.lang.Integer.parseInt(Integer.java:580)

    at java.lang.Integer.parseInt(Integer.java:615)

    at NumberFormatException.main(NumberFormatException.java:6)

    5. Attempting to Store an Incompatible Value to a Collection

    Below is an example where user has created the ArrayList of String but trying to store the integer value which leads to Exception   java.lang.Error: Unresolved compilation problem

    import java.util.ArrayList;

    public class IncompatibleType {

    public static void main(String[] args) {

    ArrayList<String> student = new ArrayList<>();

    student.add(1);

    }

    }

    Error :

    Exception in thread «main» java.lang.Error: Unresolved compilation problem:

    The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)

    at IncompatibleType.main(IncompatibleType.java:7)

    How to solve Runtime Rrror in Java Programming?

     The runtime errors can be solved by using the try catch blocks in Java. Below are the steps to be followed:

    1. You will need to Surround the statements that are capable of throwing an exception or a runtime error in the try catch blocks.
    2. The next step is to catch the error.
    3. Based on the requirements of the court or an application, it is important to take the necessary action.

    Like we discussed earlier about the ArithmeticException example, it can be corrected by making the below changes.

    public class ArithmeticExceptionExample {

    public static void main(String[] args) {

         try {

             int num1 = 10, num2 = 0;

             System.out.println(«Result: « + num1/num2);

         } catch (ArithmeticException ae) {

             System.out.println(«Arithmetic Exception — cannot divide by 0»);

         }

            System.out.println(«Let’s continue the execution…»);

    }

    }

    As the code is surrounded in the try catch blocks, the program will continue to execute after the exception is encountered.

    Result :

    Arithmetic Exception cannot divide by 0

    Lets continue the execution...

    In this way, it is important for you to identify the Runtime errors and also clear them without any hesitation. You can make use of the try catch blocks and many other resolutions which were helped in successful program execution. Also you will be able to track, manage and analyze the errors in real time. So this was all from this tutorial about fixing the 5 most common types of Runtime Errors in Java But still, if you have any queries, feel free to ask in the comment section. And don’t forget to stay tuned with the Tutorials field to learn this type of awesome tutorial. HAPPY CODING.

    People Are Also Reading…

    • How to Play Mp3 File in Java Tutorial | Simple Steps
    • Menu Driven Program in Java Using Switch Case
    • Calculator Program in Java Swing/JFrame with Source Code
    • Registration Form in Java With Database Connectivity
    • How to Create Login Form in Java Swing
    • Text to Speech in Java
    • How to Create Splash Screen in Java
    • Java Button Click Event
    • 11 Best WebSites to Learn Java Online for Free

    java.lang.ArithmeticException is Unchecked exception and sub class of java.lang.RuntimeException. It’s thrown when an exceptional condition occurred in Arithmetic Operations. It can also occurred by virtual machine as if suppression were disabled and /or the stack trace was not writable.

    Constructors:

    • ArithmeticException() : Constructs an ArithmeticException with no detail message.
    • ArithmeticException(String s) : Constructs an ArithmeticException with the specified detail message.

    Example :

    An integer value “divide by zero” throw ArithmaticException.  In below example i am dividing int, double, float and long value with 0. For long and int type value it’s throwing Arithmatic Exception while for double and float printing special value as Infinity.  See below How to fix Arithmetic Exception? section.

    package example;
    
    public class ArithmaticExceptionExample {
    
    	public static void main(String[] args) {
    		int x=0;
    		int y=5;
    		double z=6;
    		float l=6;
    		long k=10L;
    		//Integer value divide by integer value as 0 throw ArithmeticException
    		try
    		{
    			System.out.println("Integer value divide by zero");
    		System.out.println(y/x);
    		}
    		catch(ArithmeticException ex)
    		{
    			ex.printStackTrace();
    		}
    		//Double value divide by integer value as 0 No Exception special value Infinity
    		System.out.println("Double value divide by zero");
    		System.out.println(z/x);
    
    		//Float value divide by integer value as 0 No Exception special value Infinity
    		System.out.println("Float value divide by zero");
    		System.out.println(l/x);
    
    		//Long value divide by integer value as 0 throw ArithmeticException
    		try
    		{
    		System.out.println("Long value divide by zero");
    		System.out.println(k/x);
    		}
    		catch(ArithmeticException ex)
    		{
    			ex.printStackTrace();
    		}
    
    	}
    
    }
    
    

    Output:

    Integer value divide by zero
    java.lang.ArithmeticException: / by zero
    	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:15)
    Double value divide by zero
    Infinity
    Float value divide by zero
    Infinity
    Long value divide by zero
    java.lang.ArithmeticException: / by zero
    	at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:31)
    

    How to fix Arithmetic Exception?

    In above example:

    Y/X or K/X result ArithmeticException

    What happens here is that since both the dividend and the divisor are int, the operation is an integer division, whose result is rounded to an int. Remember that an int can only contain whole number (of limited range, some 4 billion numbers approximately) That’ s why throwing Arithmatic Exception. same case for long value.

    Z/X or L/X result special value Infinity

    Here float (L) or double (X) precision value  divide by zero store in float and double value that why result is special value Infinity.

    “Learn From Others Experience»

    What Is Arithmetic exception?

    Thrown when an exceptional arithmetic condition has occurred. For example, an integer “divide by zero” throws an instance of this class.

    In this tutorial, we will take a look at a few examples that will highlight the causes of getting an ArithmeticException in the Java program. Also, we will discuss the common causes of Arithmetic exception and how can we handle this exception.

    An arithmetic exception is an error that is thrown when a “wrong” arithmetic situation occurs. This usually happens when mathematical or calculation errors occur within a program during run-time. There various causes to an ArithmeticException, the following are a few of them:

    List of all invalid operations that throw an ArithmeticException() in Java

    • Dividing by an integer Zero
    • Non-terminating decimal numbers using BigDecimal

    Dividing by an integer Zero:

    Java throws an Arithmetic exception when a calculation attempt is done to divide by zero, where the zero is an integer. Take the following piece of code as an example:

    package co.java.exception;
    public class ArithmaticExceptionEx 
    {
       void divide(int a,int b)
       {
          int q=a/b;
          System.out.println("Sucessfully Divided");
          System.out.println("The Value After Divide Is :-" +q);
       }
       public static void main(String[] args) 
       {
          ArithmaticExceptionEx obj=new ArithmaticExceptionEx();
          obj.divide(10, 0);
       }
    }

    When we run the code, we get the following error:

    Exception in thread "main" java.lang.ArithmeticException: / by zero at co.java.exception.ArithmaticExceptionEx.divide(ArithmaticExceptionEx.java:7) at co.java.exception.ArithmaticExceptionEx.main(ArithmaticExceptionEx.java:14)

    Since we divided 10 by 0, where 0 is an integer, java throws the above exception. However, if the zero is a floating-point as in the following code, we get a completely different result.

    Here, no exception is thrown, and “Q” now has a value of infinity.  Note that is (almost) always a bad idea to divide by zero, even if no exception is thrown.

    Non-terminating decimal numbers using BigDecimal:

    The BigDecimal class is a Java class used to represent decimal numbers up to a very high number of precision digits. The class also offers a set of functionalities that are not available using primitive data types such as doubles and floats. These functionalities include rounding up/down, defining the number of decimal places we need from a number, etc.

    Since BigDecimals are used to represent numbers to a high degree of accuracy, a problem might occur with some numbers, for example, when dividing 1 by 3, or 2 by 12. These numbers do not have a specific number of decimal places, for example, 1/3 = 0.33333333333333333…

    Take the following program for example :

    package co.java.exception;
    import java.math.BigDecimal;
    public class ArithmeticExceptionExamples {
       public static void main(String[] args) {
          // TODO Auto-generated method stub
          BigDecimal x = new BigDecimal(1);
            BigDecimal y = new BigDecimal(3);
            x = x.divide(y);       
            System.out.println(x.toString());
       }
    }

    Take a Look On The Execution:

    In the program above, since the class doesn’t know what to do with the division result, an exception is thrown.

    Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(Unknown Source) at co.java.exception.ArithmeticExceptionExamples.main(ArithmeticExceptionExamples.java:11)

    As we said, the program doesn’t know what to do with the result of the division, hence an exception is thrown with the message “Non-terminating decimal expansion”. One possible solution to the above problem is to define the number of decimal places we require from a big decimal, and the form of rounding that will be used to limit the value to a certain number of decimals. For example, we could  say that z should be limited to 7 decimal places, by rounding up at the 7th decimal place:

    package co.java.exception;
    import java.math.BigDecimal;
    public class ArithmeticExceptionExamples {
       public static void main(String[] args) {
       // TODO Auto-generated method stub
       BigDecimal x = new BigDecimal(1);
            BigDecimal y = new BigDecimal(3);        
            x = x.divide(y, 7, BigDecimal.ROUND_DOWN);//here we limit the # of decimal places        
            System.out.println(x.toString());
       }
    }

    Here, the program runs properly, since we defined a limit to the number of places the variable “x”  could assume.

    If You Have any doubts feel free to drop your doubts in the Comment Section.

    Понравилась статья? Поделить с друзьями:
  • Division by 0 error token is
  • Divinity original sin ошибка при запуске
  • Divinity original sin ошибка подключения
  • Divinity original sin код ошибки 504
  • Divinity original sin как изменить характеристики