C

Core Java tutorial for beginners

Clean • Professional

Java Exception – Definition, Examples & Handling

1 minute

What is an Exception in Java?

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.


Why Exceptions Occur?

Exceptions occur due to invalid operations, such as:

  • Dividing a number by zero
  • Accessing an array index out of range
  • Opening a file that doesn’t exist
  • Passing null where an object is required
  • Type conversion errors
  • Network or database failure

Example: Without Exception Handling

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);
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Program crashes and stops executing.


How Java Handles Exceptions?

When an exception occurs:

  1. Java creates an Exception object
  2. Passes (throws) it to the JVM
  3. JVM looks for a matching catch block
  4. If not found → program terminates abnormally

Exception vs Error

FeatureExceptionError
TypeRecoverableNon-recoverable
ExamplesArithmeticException, NullPointerExceptionOutOfMemoryError, StackOverflowError
Programmer Can Handle?YESNO
Packagejava.lang.Exceptionjava.lang.Error

Exception Hierarchy

Throwable
│
├── Exception  → can be handled
│     ├── RuntimeException
│     └── IOException, SQLException etc.
│
└── Error      → cannot be handled

Real-Life Analogy

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.


Why Exception Handling is Needed?

  • Prevents program crashes
  • Displays meaningful error messages
  • Allows graceful program recovery
  • Helps debugging
  • Makes applications more stable & user-friendly

Article 0 of 0