Home

 › 

Articles

 › 

3 Types of Errors in Java (With Examples for Each One)

types of errors in java

3 Types of Errors in Java (With Examples for Each One)

It could have happened to you once before. Perhaps it’s even happened more times than you care to recall. You’ve spent countless hours working on your Java project, meticulously crafting each line of code. But just as you hit the “Run” button, your excitement quickly turns to dread as a barrage of Java error messages gets spat out on your screen. 

Let’s face it: errors are an inevitable part of programming. We can’t always ship perfect code and this is certainly frustrating, but it’s just a part of the job. With time and experience, however, we learn to anticipate and resolve them more efficiently. In the meantime, it’s important to understand the different types of errors you might encounter in Java.

In this comprehensive guide, we’ll explore the various types of errors that can occur in your Java code, complete with examples and solutions to help you tackle them head-on. Let’s get right into it.

1. Syntax Errors

Syntax errors are easily the most common type we encounter. These pesky errors occur when your code violates the rules of a programming language. Different languages have different syntactical rules and it just so happens that Java is one of the stricter languages.

Also known as compile-time errors, syntax errors occur when the compiler tries to parse your code. For instance, forgetting a semicolon at the end of a statement or misspelling a variable name can lead to syntax errors.

Often, the error messages will point you in the right direction of what went wrong. For example, if you see a “missing semicolon” error message, you’ll know exactly what to look for in your code.

public class Main {
    public static void main(String[] args) {
        int a = 10;
        System.out.println("The value of a is: " + a)
    }
}

The above code results in the following error:

/Main.java:4: error: ';' expected
        System.out.println("The value of a is: " + a)
                                                    ^
1 error

We forgot to add a semicolon after the println statement, causing the ‘;’ expected error to be thrown.

To fix most syntax errors, simply make sure you understand the error message, go back to your code and debug, and recompile your code. After adding the missing semicolon, we get the following output:

The value of a is: 10

Here’s another example:

public class Main {
    public static void main(String[] args) {
        int a = 10;
        b = 20; 
        System.out.println(a + b);
    }
}

If we run the above code, we get the following:

/Main.java:4: error: cannot find symbol
        b = 20; 
        ^
  symbol:   variable b
  location: class Main
/Main.java:5: error: cannot find symbol
        System.out.println(a + b);
                               ^
  symbol:   variable b
  location: class Main
2 errors

In this case, we forgot to declare the variable b, so the compiler throws an error because it cannot find the symbol in the class Main. We fix all this by modifying the line b = 20 to int b = 20; to get “30” as the result.

2. Runtime Errors

Runtime errors, also known as runtime exceptions, occur during the execution of your code. These errors occur when your code tries to perform an operation that is not allowed, or when it encounters invalid/ unexpected input or conditions.

These could be anything from dividing by zero to accessing an array index that doesn’t exist. Unlike syntax errors, runtime errors are not caught by the compiler and can only be detected during program execution. 

ArrayIndexOutOfBoundsException Errors

A common example of a runtime error is the dreaded ArrayIndexOutOfBoundsException, which occurs when you try to access a Java array element that doesn’t exist:

public class Example {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        System.out.println(numbers[3]);
    }
}

In this code, we are trying to access the fourth element of an array that only has three elements. When we run this code, we get the following error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at Main.main(Main.java:4)

To fix this error, we need to ensure that we only access elements that exist in the array. So, if we use System.out.println(numbers[2]) instead, we get “3” as the output since it’s the third element in the array.

To zero in on potential runtime errors, you could also use try-catch blocks to catch and handle exceptions much more easily, getting the errors in a more meaningful format:

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        try {
            System.out.println(numbers[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: Index is out of bounds!");
        }
    }
}

If an exception is thrown, the catch block will execute, which simply prints an error message to the console:

Error: Index is out of bounds!

ArithmeticException Errors

As the name implies, ArithmeticException runtime errors occur when we attempt to do something mathematically impossible, such as dividing a number by zero. The following code illustrates this:

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int c = a / b; 
        System.out.println("The value of c is: " + c);
    }
}

Running it results in the JRE (Java Runtime Environment), throwing the following error:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.main(Main.java:5)

If anticipating such an error, we can always modify the code and use a try-catch block and display a meaningful message instead of letting the program crash.

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try {
            int c = a / b;
            System.out.println("The value of c is: " + c);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Running this results in the expected result:

Error: / by zero

Other Types of Runtime Errors in Java

There are multiple runtime errors in Java. Some of the other common runtime errors include the following:

  1. NullPointerException: A NullPointerException error occurs when you try to use an object reference that has not been initialized. For example, if you try to call a method on a null object, you will get a NullPointerException.
  1. ClassCastException: This error occurs when you try to cast an object to a type that it is not compatible with, such as when you try to cast a String to an Integer.
  1. StackOverflowError: This happens when the stack overflows due to too many method calls. This can happen if you have a recursive method that calls itself too many times.

3. Logical Errors

Logical errors occur when your program runs without any errors, but doesn’t produce the expected output. These types of errors in Java or other programming languages can be pretty to detect because the program runs without any apparent errors.

These errors are often caused by incorrect assumptions or flawed logic in the program’s design. Let’s consider the following function:

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        int c = a - b;
        if (c > 0) {
            System.out.println("a is greater than b");
        } else {
            System.out.println("b is greater than a");
        }
    }
}

In the code above, we compare the values of ‘a’ and ‘b’ and print a message based on which value is greater. However, we made a mistake in the logic. If ‘c’ is zero, it means that ‘a’ and ‘b’ are equal, but our code doesn’t handle that scenario.

So, if we run the code when a and b are equal, nothing gets logged and we’d have no idea what happened. We can fix the logical error by adding another condition to handle this case.

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        int c = a - b;
        if (c > 0) {
            System.out.println("a is greater than b");
        } else if (c < 0) {
            System.out.println("b is greater than a");
        } else {
            System.out.println("a and b are equal");
        }
    }
}

If we therefore run the code with, say a = 10 and b = 10, we get the result:

a is greater than b

Let’s now look at some things you could do to handle errors more effectively.

Best Practices for Handling Different Types of Errors in Java

When catching exceptions, it is important to catch the most specific exception first. This means that you should catch the exception that is most specific to the error that you are trying to handle. This is because if you catch a more general exception first, it might mask more specific errors with generic ones.

Another useful tool is the Java compiler itself, which can be run in “linting” mode to check your code for potential runtime or logical errors. This can be especially helpful if you’re working on a large codebase and want to catch errors early in the development process.

Or as we did with some previous cases, logging exceptions with descriptive messages using try-catch blocks can be helpful to enhance maintainability and facilitate issue diagnosis.

Besides using the compiler’s error messages to help you find and fix syntax errors, there are also tools that can help you catch them before you even run your code.

Integrated Development Environments (IDEs) such as Eclipse or IntelliJ IDEA have built-in code analysis tools that can highlight potential syntax errors as you type.

In some cases, you might need to do deeper debugging to resolve the error. Just be systematic about it. Start by carefully reviewing the line of code where the error occurred, paying attention to any underlined or highlighted sections.

Rounding Up

Getting a handle on the different types of errors in Java is crucial for writing effective code and building robust applications. As we’ve seen, there are three main types; namely, syntax, runtime, and logical error. Each of these is important to understand, as they can affect the behavior of your program in different ways.

By understanding the ins and outs of each one of them, you’ll be well-equipped to debug and resolve issues in your code. Remember to follow the tips and best practices we’ve discussed. Not only will you be well on your way to writing readable and maintainable code, but you will hone your Java programming skills.

3 Types of Errors in Java (With Examples for Each One) FAQs (Frequently Asked Questions) 

What are the main types of errors in Java?

The main types of errors in Java are syntax, runtime, and logical errors. Syntax errors occur when the code violates Java’s syntax rules, while runtime errors happen during the execution of the program. Logical errors are mistakes in the program’s logic that produce incorrect results.

What is the difference between an error and an exception in Java?

In Java, errors are typically serious issues that cannot be handled by the application, such as virtual machine errors. Exceptions, on the other hand, are issues that can be caught and handled by the application, such as null pointer exceptions.

What are the modern exception handling techniques in Java?

Some modern exception-handling techniques in Java involve using lambda expressions and try-with-resources statements to handle exceptions more effectively and simplify development.

Are there buffer overflow errors in Java? How are they different from stack overflow errors?

Buffer overflow errors in Java are rare because Java automatically manages memory allocation and deallocation. However, stack overflow errors can occur when a program uses excessive recursion or consumes too much stack memory, causing the stack to overflow.

To top