Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

In Java, Exception and Error are both subclasses of the Throwable class and represent events that disrupt the normal flow of program execution. However, there is a significant difference in their purpose and handling.

Exception:

  • Represents an event that can occur during program execution and which should generally be handled.
  • Results from problems related to the program code or external environment (e.g., invalid input, missing file).
  • Divided into two types:
    • Checked Exceptions: Inherit from Exception (but not from RuntimeException). The compiler checks for their presence and requires explicit handling (try-catch) or declaration (throws). Examples: IOException, SQLException.
    • Unchecked Exceptions: Inherit from RuntimeException or Error. The compiler does not require explicit handling. Usually indicate logical errors in code. Examples: NullPointerException, ArrayIndexOutOfBoundsException.

Error:

  • Represents a serious problem indicating a failure at the system level and generally cannot be recovered or handled by the program.
  • Results from problems outside the control of the program (e.g., JVM out of memory, virtual machine failure).
  • Usually indicate resource issues or JVM problems.
  • The program should not attempt to catch or handle errors.
  • Examples: OutOfMemoryError, StackOverflowError, VirtualMachineError.

Comparison Table:

Aspect Exception Error
Purpose Problems related to program code or external environment Serious system-level problems
Handling Can and should be handled by the program (try-catch) Usually cannot be handled by the program
Recovery Possible after handling Usually impossible to recover
Problem type Logical errors, I/O issues, network errors Resource problems, JVM failures
Compiler check Requires explicit handling/declaration for Checked Exceptions No explicit handling/declaration required
Examples IOException, NullPointerException, SQLException OutOfMemoryError, StackOverflowError, LinkageError

Example of a Checked Exception:

// Example of Checked Exception
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {

    public static void main(String[] args) {
        try {
            readFile("non_existent_file.txt");
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }

    public static void readFile(String filename) throws IOException {
        File file = new File(filename);
        FileReader fr = new FileReader(file);
        int charCode;
        while ((charCode = fr.read()) != -1) {
            System.out.print((char) charCode);
        }
        fr.close();
    }
}

Example of an Unchecked Exception:

// Example of Unchecked Exception
public class UncheckedExceptionExample {

    public static void main(String[] args) {
        String str = null;
        try {
            System.out.println(str.length()); // NullPointerException
        } catch (NullPointerException e) {
            System.err.println("Caught NullPointerException: " + e.getMessage());
        }

        int[] numbers = {1, 2, 3};
        try {
            System.out.println(numbers[10]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
        }
    }
}

Example of Error:

// Example of Error (Out of Memory)
import java.util.ArrayList;
import java.util.List;

public class ErrorExample {

    public static void main(String[] args) {
        List<byte[]> list = new ArrayList<>();
        try {
            while (true) {
                list.add(new byte[1024 * 1024]); // Trying to allocate a lot of memory
            }
        } catch (OutOfMemoryError e) {
            System.err.println("Caught OutOfMemoryError: " + e.getMessage());
            // Further program operation is likely impossible
        }
    }
}
What is the difference between an exception and an… - sobes.tech