Java Exceptions and Exception Handling
What is an Exception?
An exception is an error that happens while a program
is running. When something goes wrong (like dividing a
number by zero, accessing an invalid array index, or
opening a file that doesn’t exist), Java creates an
exception object. If not handled, the program will stop
suddenly (crash).
Example (without handling):
int a = 10, b = 0;
int c = a / b; // This will cause ArithmeticException
(divide by zero)
[Link]("Result: " + c);
What is Exception Handling?
Exception handling is the way to catch the error and
deal with it, so the program does not stop suddenly. In
Java, we use try-catch blocks.
Example (with handling):
try {
int c = a / b; // risky code
[Link]("Result: " + c);
}
catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
}
[Link]("Program continues after handling
exception.");
Types of Exceptions in Java
Java exceptions are mainly of two types:
1. Checked Exceptions
These are exceptions that the compiler knows about
and forces you to handle. You must use try-catch or
throws for them.
Examples: FileNotFoundException, IOException
2. Unchecked Exceptions (Runtime Exceptions)
These happen while the program runs. The compiler
does not force you to handle them.
Examples: ArithmeticException,
ArrayIndexOutOfBoundsException,
NullPointerException
3. Errors (Not Exceptions)
Errors are serious problems that programs usually
cannot recover from (like system crash or memory full).
Examples: OutOfMemoryError, StackOverflowError.
Normally, we do not handle them in code.