Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Exceptions in Java
Introduction



When you run a Java program, sometimes things go wrong. Maybe you're trying to divide a number by zero, or you're reading a file that doesn't exist. In Java, these "unexpected events" are called exceptions.

What is an Exception?

An exception is an event that disrupts the normal flow of a program. It’s a runtime error — something Java didn’t expect to happen while your code was running.

For example:

public class DivideByZero {
    public static void main(String[] args) {
        int result = 10 / 0;
        System.out.println("Result: " + result);
    }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero

Notice that Java didn’t just crash silently. It gave a detailed message — the type of error and the line where it happened. That’s part of what makes Java’s exception system so developer-friendly.

Types of Exceptions in Java

1. Checked Exceptions

These are exceptions that Java forces you to handle at compile time. They typically deal with external resources like files, databases, or network connections.

import java.io.File;
import java.io.FileReader;

public class CheckedExample {
    public static void main(String[] args) throws Exception {
        File file = new File("myfile.txt");
        FileReader reader = new FileReader(file); // May throw FileNotFoundException
    }
}

Java won't compile this code unless you either handle the exception with a try-catch block or declare it with throws.

2. Unchecked Exceptions

These are runtime exceptions, and Java does not require you to catch or declare them. Common examples include:

public class UncheckedExample {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.length()); // NullPointerException
    }
}
Exception in thread "main" java.lang.NullPointerException

Java Exception Hierarchy

All exceptions are part of the Throwable class. Here's a simplified view:

How to Handle Exceptions in Java

1. try-catch Block

This is the most common way to catch exceptions.

public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Caught an exception: " + e.getMessage());
        }
    }
}
Caught an exception: / by zero

2. Multiple catch Blocks

Different exceptions can be caught separately.

public class MultiCatchExample {
    public static void main(String[] args) {
        try {
            int[] nums = {1, 2};
            System.out.println(nums[5]);
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index error");
        }
    }
}
Array index error

3. finally Block

This block always runs, whether or not there’s an exception. It's used for cleanup operations.

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int x = 5 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Handled exception.");
        } finally {
            System.out.println("Finally block always runs.");
        }
    }
}
Handled exception.
Finally block always runs.

Using throw to Manually Raise an Exception

public class ThrowExample {
    public static void main(String[] args) {
        throw new IllegalArgumentException("This is not allowed!");
    }
}
Exception in thread "main" java.lang.IllegalArgumentException: This is not allowed!

Using throws to Declare an Exception

If you want to let the caller handle an exception, you can declare it using throws.

import java.io.FileReader;

public class ThrowsExample {
    public static void main(String[] args) throws Exception {
        FileReader reader = new FileReader("nofile.txt");
    }
}
Exception in thread "main" java.io.FileNotFoundException: nofile.txt (No such file or directory)

Summary

QUIZ

Question 1:What happens when a Java program encounters an unexpected error like division by zero?

Question 2:Unchecked exceptions must be handled at compile time in Java.

Question 3:Which of the following are valid characteristics of checked exceptions in Java?

Question 4:Which of the following best describes the purpose of a `finally` block in Java?

Question 5:The `throw` keyword is used in Java to declare that a method might raise an exception.

Question 6:Which of the following are true about Java exception hierarchy?



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M