Clean β’ Professional
An exception in Java is an unexpected event that occurs during the execution of a program and interrupts the normal flow of instructions. It is not a compile-time error, it happens at runtime.
Simple Definition
An exception is a runtime problem that stops program execution unless handled properly.
Exceptions occur due to invalid operations, such as:
public class Example {
public static void main(String[] args) {
int a = 10;
int b = 0;
int result = a / b; // Exception occurs here
System.out.println(result);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
Program crashes and stops executing.
When an exception occurs:
| Feature | Exception | Error |
|---|---|---|
| Type | Recoverable | Non-recoverable |
| Examples | ArithmeticException, NullPointerException | OutOfMemoryError, StackOverflowError |
| Programmer Can Handle? | YES | NO |
| Package | java.lang.Exception | java.lang.Error |
Throwable
β
βββ Exception β can be handled
β βββ RuntimeException
β βββ IOException, SQLException etc.
β
βββ Error β cannot be handled
If your laptop suddenly shuts down while working β this interruption is similar to a Java exception.
If your laptopβs motherboard burns β itβs like a Java Error β cannot be handled.