Junior
What is the difference between an error and an exception?
sobes.tech AI
Answer from AI
Error represents an unrecoverable problem that occurs outside the control of the application. It is usually related to JVM resources (for example, stack overflow or out of memory). The application cannot recover from such a problem.
Exception represents a problem that can potentially be handled by the application. It occurs during program execution and can be caused by various reasons, such as incorrect user data, loss of network connection, or an attempt to access a non-existent file.
Main differences:
| Characteristic | Error | Exception |
|---|---|---|
| Recoverability | Unrecoverable problem | Potentially recoverable problem |
| Control | Outside the control of the application | Can be handled by the application |
| Inheritance | Inherits from java.lang.Error |
Inherits from java.lang.Exception |
| Handling | Usually not caught explicitly (unchecked) | Can be caught and handled (checked/unchecked) |
Examples:
// Error example
public class StackOverflow {
public static void recursiveMethod() {
recursiveMethod(); // Infinite recursion causes StackOverflowError
}
public static void main(String[] args) {
recursiveMethod();
}
}
// Exception example
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileRead {
public static void main(String[] args) {
try {
File file = new File("nonexistent_file.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage()); // Exception handling
}
}
}