Friday, December 27, 2024
Google search engine
HomeLanguagesJavaTypes of Errors in Java with Examples

Types of Errors in Java with Examples

Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. 

The most common errors can be broadly classified as follows:

1. Run Time Error: 

Run Time errors occur or we can say, are detected during the execution of the program. Sometimes these are discovered when the user enters an invalid data or data which is not relevant. Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do. During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running. To handle the error during the run time we can put our error code inside the try block and catch the error inside the catch block. 

For example: if the user inputs a data of string format when the computer is expecting an integer, there will be a runtime error. Example 1: Runtime Error caused by dividing by zero 

Java




// Java program to demonstrate Runtime Error
 
class DivByZero {
    public static void main(String args[])
    {
        int var1 = 15;
        int var2 = 5;
        int var3 = 0;
        int ans1 = var1 / var2;
 
        // This statement causes a runtime error,
        // as 15 is getting divided by 0 here
        int ans2 = var1 / var3;
 
        System.out.println(
            "Division of va1"
            + " by var2 is: "
            + ans1);
        System.out.println(
            "Division of va1"
            + " by var3 is: "
            + ans2);
    }
}


Runtime Error in java code:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at DivByZero.main(File.java:14)

Example 2: Runtime Error caused by Assigning/Retrieving Value from an array using an index which is greater than the size of the array 

Java




class RTErrorDemo {
    public static void main(String args[])
    {
        int arr[] = new int[5];
 
        // Array size is 5
        // whereas this statement assigns
 
        // value 250 at the 10th position.
        arr[9] = 250;
 
        System.out.println("Value assigned! ");
    }
}


RunTime Error in java code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at RTErrorDemo.main(File.java:10)

2. Compile Time Error: 

Compile Time Errors are those errors which prevent the code from running because of an incorrect syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. These errors are detected by the java compiler and an error message is displayed on the screen while compiling. Compile Time Errors are sometimes also referred to as Syntax errors. These kind of errors are easy to spot and rectify because the java compiler finds them for you. The compiler will tell you which piece of code in the program got in trouble and its best guess as to what you did wrong. Usually, the compiler indicates the exact line where the error is, or sometimes the line just before it, however, if the problem is with incorrectly nested braces, the actual error may be at the beginning of the block. In effect, syntax errors represent grammatical errors in the use of the programming language. 

Example 1: Misspelled variable name or method names 

Java




class MisspelledVar {
    public static void main(String args[])
    {
        int a = 40, b = 60;
 
        // Declared variable Sum with Capital S
        int Sum = a + b;
 
        // Trying to call variable Sum
        // with a small s ie. sum
        System.out.println(
            "Sum of variables is "
            + sum);
    }
}


Compilation Error in java code:

prog.java:14: error: cannot find symbol
            + sum);
              ^
  symbol:   variable sum
  location: class MisspelledVar
1 error

Example 2: Missing semicolons 

Java




class PrintingSentence {
    public static void main(String args[])
    {
        String s = "Lazyroar";
 
        // Missing ';' at the end
        System.out.println("Welcome to " + s)
    }
}


Compilation Error in java code:

prog.java:8: error: ';' expected
        System.out.println("Welcome to " + s)
                                             ^
1 error

Example: Missing parenthesis, square brackets, or curly braces 

Java




class MissingParenthesis {
    public static void main(String args[])
    {
        System.out.println("Printing 1 to 5 \n");
        int i;
 
        // missing parenthesis, should have
        // been for(i=1; i<=5; i++)
        for (i = 1; i <= 5; i++ {
 
            System.out.println(i + "\n");
        } // for loop ends
 
    } // main ends
} // class ends


Compilation Error in java code:

prog.java:10: error: ')' expected
        for (i = 1; i <= 5; i++ {
                               ^
1 error

Example: Incorrect format of selection statements or loops 

Java




class IncorrectLoop {
    public static void main(String args[])
    {
 
        System.out.println("Multiplication Table of 7");
        int a = 7, ans;
        int i;
 
        // Should have been
        // for(i=1; i<=10; i++)
        for (i = 1, i <= 10; i++) {
            ans = a * i;
            System.out.println(ans + "\n");
        }
    }
}


Compilation Error in java code:

prog.java:12: error: not a statement
        for (i = 1, i <= 10; i++) {
                      ^
prog.java:12: error: ';' expected
        for (i = 1, i <= 10; i++) {
                                ^
2 errors

Logical Error: A logic error is when your program compiles and executes, but does the wrong thing or returns an incorrect result or no output when it should be returning an output. These errors are detected neither by the compiler nor by JVM. The Java system has no idea what your program is supposed to do, so it provides no additional information to help you find the error. Logical errors are also called Semantic Errors. These errors are caused due to an incorrect idea or concept used by a programmer while coding. Syntax errors are grammatical errors whereas, logical errors are errors arising out of an incorrect meaning. For example, if a programmer accidentally adds two variables when he or she meant to divide them, the program will give no error and will execute successfully but with an incorrect result. 

Example: Accidentally using an incorrect operator on the variables to perform an operation (Using ‘/’ operator to get the modulus instead using ‘%’) 

Java




public class LErrorDemo {
    public static void main(String[] args)
    {
        int num = 789;
        int reversednum = 0;
        int remainder;
 
        while (num != 0) {
 
            // to obtain modulus % sign should
            // have been used instead of /
            remainder = num / 10;
            reversednum
                = reversednum * 10
                  + remainder;
            num /= 10;
        }
        System.out.println("Reversed number is "
                           + reversednum);
    }
}


Output:

Reversed number is 7870

Example: Displaying the wrong message 

Java




class IncorrectMessage {
    public static void main(String args[])
    {
        int a = 2, b = 8, c = 6;
        System.out.println(
            "Finding the largest number \n");
 
        if (a > b && a > c)
            System.out.println(
                a + " is the largest Number");
        else if (b > a && b > c)
            System.out.println(
                b + " is the smallest Number");
 
        // The correct message should have
        // been System.out.println
        //(b+" is the largest Number");
        // to make logic
        else
            System.out.println(
                c + " is the largest Number");
    }
}


Output:

Finding the largest number 

8 is the smallest Number

Syntax Error:

Syntax and Logical errors are faced by Programmers.

Spelling or grammatical mistakes are syntax errors, for example, using an uninitialized variable, using an undefined variable, etc., missing a semicolon, etc.

int x, y;
x = 10 // missing semicolon (;)
z = x + y; // z is undefined, y in uninitialized.

Syntax errors can be removed with the help of the compiler.

RELATED ARTICLES

Most Popular

Recent Comments