top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Error vs. Exception in Java

Overview

Any beginner will face problems when they start their Java programming journey. The problems thrown are usually errors or exceptions in Java. It is imperative to have basic knowledge about error vs. exception in Java.

In this tutorial, we will learn how to manage errors vs. exceptions in Java.

What Are Errors?

Errors are special circumstances that normally cannot be repaired and denote major issues prohibiting the program from running properly in Java. Errors are frequently brought on by outside variables or serious internal problems with the Java Virtual Machine (JVM). Here are a few typical Java errors:

  • OutOfMemoryError

  • StackOverflowError

  • NoClassDefFoundError

  • NoSuchMethodError

  • AbstractMethodError

It's crucial to keep in mind that errors often aren't intended to be detected and addressed by the application code because they typically point to serious issues. Instead, the JVM or underlying system is designed to detect and manage faults to ensure the program's stability.

Examples of Errors

  • StackOverflowError

This error occurs when the call stack used to track method calls exceeds its limit due to infinite recursion.

public class upGradTutorials {
    public static void recursiveMethod() {
        recursiveMethod();
    }

    public static void main(String[] args) {
        recursiveMethod();
    }
}
  • OutOfMemoryError

This error occurs when the Java Virtual Machine (JVM) cannot allocate more memory for an object because the heap space is exhausted.

public class upGradTutorials {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        while (true) {
            numbers.add(1);
        }
    }
}

(output in local development environment)

  • NoClassDefFoundError

The NoClassDefFoundError is a runtime error that occurs when the JVM cannot find a class that was present during compilation. 

public class upGradTutorials {
    public static void main(String[] args) {
        NonExistentClass obj = new NonExistentClass();
    }
}

(output in local development environment)

  • NoSuchMethodError

This error occurs when the JVM cannot find a referenced method at runtime.

public class upGradTutorials {
    public static void main(String[] args) {
        String str = "upGrad teaches Java.";
        int length = str.getLength(); //
        System.out.println(length);
    }
}

(output in local development environment)

  • AbstractMethodError

This error occurs when a subclass fails to provide an implementation for an abstract method declared in its superclass or interface.

(upGradTutorials.java file)

public class upGradTutorials extends AbstractClass {
    public static void main(String[] args) {
        upGradTutorials obj = new upGradTutorials();
        obj.abstractMethod();
    }
}

(AbstractClass.java file)

public abstract class AbstractClass {
    public abstract void abstractMethod();
}

(output in local development environment)

What Are Exceptions?

Exceptions are objects that indicate extraordinary circumstances that arise while a programme is being executed in Java. These circumstances alter the program's typical flow and can call for special intervention. Exceptions offer a way to deal with and move past these extraordinary circumstances.

Checked exceptions and unchecked exceptions are the two categories into which exceptions in Java are split.

  • Checked Exceptions: The Java compiler mandates that the programmer explicitly manage these errors by using try-catch blocks or stating them in the method signature using the throws keyword. Checked exceptions are frequently used to illustrate anticipated mistakes or extraordinary circumstances that are fairly repairable. IOException, SQLException, and ClassNotFoundException are a few examples of checked exceptions.

  • Unchecked Exceptions: The compiler does not require the programmer to handle these exceptions explicitly. Unchecked exceptions are typically brought about by mistakes in programming or unforeseen circumstances that the programmer is not expected to address. They are RuntimeException or Error subclasses, and while it is possible to catch and handle them, it is not required. NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException are a few examples of unchecked exceptions.

The Java runtime creates an exception object when an unusual condition occurs, which stores details about the error, including the kind of exception, a description, and the status of the program at the time. The program then passes control to a particular section of code known as an exception handler after throwing the exception object.

Examples of Exception

1. ClassNotFoundException

public class upGradTutorials {
    public static void main(String[] args) {
        try {
            Class.forName("com.example.NonExistentClass");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

In this example, we try to load a class com.example.NonExistentClass using Class.forName(). However, since the class doesn't exist, the compiler will detect this during compilation and raise a ClassNotFoundException. The catch block is included to handle the exception and print the stack trace.

2. ArrayIndexOutOfBoundsException

public class upGradTutorials {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        int value = numbers[3];
    }
}

In this example, we attempt to access the element at index 3 in the array numbers. However, since the valid indices for this array are 0, 1, and 2, the compiler will detect this out-of-bounds access during compilation and raise an ArrayIndexOutOfBoundsException.

3. NullPointerException

public class upGradTutorials {
    public static void main(String[] args) {
        String str = null;
        int length = str.length();
        System.out.println(length);
    }
}

In this example, we initialize the variable str with null. Then, we try to call the length() method on str, which results in a NullPointerException because we are invoking a method on a null reference.

4. ArithmeticException

public class upGradTutorials {
    public static void main(String[] args) {
        int result = divide(10, 0); // Dividing by zero
        System.out.println(result);
    }
    
    public static int divide(int a, int b) {
        return a / b;
    }
}

In this example, we have a method divide that takes two integers and performs division. We attempt to divide 10 by 0, which is not allowed and leads to an ArithmeticException.

Managing Errors and Exceptions in Java

  • Handling a StackOverflowError

In the above code, we have the recursiveMethod that calls itself recursively without any base case to stop the recursion. As a result, the method keeps calling itself indefinitely, eventually causing a StackOverflowError when the call stack exceeds its limit.

Running this code will throw a StackOverflowError and terminate the program abruptly without any handling or recovery. It's important to handle or prevent StackOverflowError when writing production code to ensure the stability and reliability of your application.

Now, let us handle this error:

To handle the StackOverflowError, we use a try-catch block in the main method. We catch the StackOverflowError and print a message indicating the error was caught. Inside the catch block, you can handle any necessary error or take appropriate action based on your application's requirements.

Code:

public class upGradTutorials {
    public static void main(String[] args) {
        try {
            recursiveMethod(0);
        } catch (StackOverflowError e) {
            System.out.println("Caught StackOverflowError: " + e.getMessage());
            // Handle the exception or take appropriate action
        }
    }

    public static void recursiveMethod(int i) {
        System.out.println("Iteration: " + i);
        recursiveMethod(i + 1); // Recursive call
    }
}
  • Handling a ClassNotFoundException

In the above code, we use the Class.forName() method to attempt to load a class that does not exist (com.example.NonExistentClass). Since the class does not exist, it will throw a ClassNotFoundException. When this exception is thrown and not handled, the program will terminate abruptly and display an error message indicating the class was not found.

Now, let us handle this exception:

In this code, we use the Class.forName() method to attempt to load a class that does not exist (com.example.NonExistentClass). Since the class does not exist, it will throw a ClassNotFoundException.

To handle this exception, we surround the Class.forName() statement with a try-catch block. If the class is not found, the catch block is executed. In this example, we simply print a message indicating that the class was not found, but you can customize the handling logic based on your requirements.

Handling the ClassNotFoundException allows your program to gracefully handle the situation when a required class is missing and provides an opportunity to handle the exception or take appropriate action, such as logging an error, displaying a user-friendly message, or providing an alternative behavior.

Code:

public class upGradTutorials {
    public static void main(String[] args) {
        try {
            // Attempt to load a class that does not exist
            Class<?> cls = Class.forName("com.example.NonExistentClass");
            System.out.println("Class loaded: " + cls.getName());
        } catch (ClassNotFoundException e) {
            System.out.println("Class not found: " + e.getMessage());
            // Handle the exception or take appropriate action
        }
    }
}

Error and Exception in Java Difference

Errors and exceptions are distinct concepts in the Java programming language. The key difference in errors and exceptions in Java is as follows:

Properties

Error

Exception

Causes

Errors result from major issues that are normally out of the application's control and frequently point to fundamental flaws with the JVM or the underlying system. OutOfMemoryError and StackOverflowError are two examples of errors.


On the other hand, exceptions are brought on by extraordinary circumstances that arise throughout the course of the program's execution and can be handled and overcome. They stand for unforeseen events or runtime faults the programmer can foresee and fix.

Recovery

Errors typically cannot be fixed quickly because they signify serious issues that frequently result in program cancellation.

On the other side, exceptions offer a method for handling errors and recovering from them. You can gracefully handle uncommon circumstances, present error messages or alternate behaviors, and continue program execution by capturing and handling exceptions.

Types

Errors are always unchecked.

Exceptions can be checked and unchecked.

Package

It belongs to java.lang.Error package.

It belongs to java.lang.Exception package.

Conclusion

Errors are serious issues that frequently point to faults with the JVM or the underlying system and are not meant to be detected and managed by application code. On the other hand, exceptions are used to manage extraordinary circumstances that arise during the execution of the program and offer a means of recovering from them. While the JVM or system often handles mistakes, exceptions can be caught and regulated by the programmer using try-catch blocks or propagated up the call stack.

Checking out a specially curated course from upGrad can help you get a better understanding of various Java concepts.

FAQs

1. What is exception propagation in Java?

In Java, the process by which an exception thrown in one method can be forwarded up the call stack to be captured and handled by the proper exception handler in a higher-level function is known as exception propagation.

2. How do you handle checked exceptions?

In Java, there are two ways to handle checked exceptions: either you can catch the exception using a try-catch block, or you may declare the exception to be thrown by using the “throws” keyword in the method signature.

3. What happens when an exception is thrown by the main method?

The default Java exception handling mechanism is used when an exception is thrown by the main method. The behavior, however, relies on whether the exception is a checked exception or an unchecked exception if it is not captured and handled within the main function itself.

Leave a Reply

Your email address will not be published. Required fields are marked *