Java Errors and Exceptions
In Java, errors and exceptions are problems that occur during program execution.
Java provides a powerful mechanism called Exception Handling to handle runtime problems.
1. What is an Error?
An Error is a serious problem that usually cannot be handled by the program.
- Occurs due to system failure.
- Caused by JVM problems.
- Program cannot recover easily.
// Example (OutOfMemoryError)
int[] arr = new int[999999999];
2. What is an Exception?
An Exception is a problem that occurs during program execution and can be handled.
- Occurs at runtime.
- Can be caught and handled.
- Prevents program from crashing.
Types of Exceptions
1. Checked Exception
Checked exceptions are checked at compile time.
- Must be handled using try-catch.
- Example: IOException, SQLException.
2. Unchecked Exception
Unchecked exceptions occur at runtime.
- Not checked at compile time.
- Example: ArithmeticException, NullPointerException.
Common Exceptions
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
- NumberFormatException
- IOException
3. try-catch Block
The try block contains risky code.
The catch block handles the exception.
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
4. finally Block
The finally block always executes whether exception occurs or not.
try {
int a = 5;
} catch (Exception e) {
System.out.println("Error");
} finally {
System.out.println("Always executed");
}
5. throw Keyword
The throw keyword is used to manually throw an exception.
throw new ArithmeticException("Invalid number");
6. throws Keyword
The throws keyword declares exceptions in method signature.
public void readFile() throws IOException {
// file reading code
}
Difference Between Error and Exception
- Error is serious and cannot be handled easily.
- Exception can be handled using try-catch.
- Error occurs at system level.
- Exception occurs in application code.
Why Exception Handling is Important?
- Prevents program crash.
- Improves program reliability.
- Makes debugging easier.
- Handles runtime errors safely.
Important Points
- All exceptions are subclasses of Throwable class.
- Use specific catch blocks instead of generic ones.
- Always close resources (use finally or try-with-resources).
- Checked exceptions must be handled.
Conclusion
Errors and Exceptions are common in Java programs.
Errors are serious system problems, while exceptions are manageable runtime problems.
Using try-catch-finally blocks helps create stable and reliable Java applications.