Labs ICT
โญ Pro Login

Exceptions

Things go wrong in programs. A file you try to read might not exist. A user might enter text when you expected a number. The network might drop. In Java, when something goes wrong, the program throws an exception.

Think of an exception as Java's way of saying "Hey, something bad happened and I cannot continue normally." If you do not handle the exception, your program crashes.

Checked vs Unchecked Exceptions

Java divides exceptions into two categories:

  • Checked exceptions โ€” the compiler forces you to handle them. They happen when something outside your control goes wrong, like a missing file or network error.
  • Unchecked exceptions โ€” the compiler does not force you to handle them. They are usually bugs in your code, like dividing by zero or accessing an array index that does not exist.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    try {
      File f = new File("data.txt");
      Scanner sc = new Scanner(f);
    } catch (FileNotFoundException e) {
      System.out.println("File not found");
    }
  }
}

FileNotFoundException is a checked exception. If I did not wrap it in a try-catch, Java would refuse to compile this code.

Common Unchecked Exceptions

These are the ones you will run into most often as a beginner. They usually mean you made a mistake somewhere.

public class Main {
  public static void main(String[] args) {
    int[] numbers = {1, 2, 3};
    System.out.println(numbers[5]);
  }
}

This throws an ArrayIndexOutOfBoundsException. The array has only three elements (indexes 0, 1, and 2), but we tried to access index 5.

public class Main {
  public static void main(String[] args) {
    String name = null;
    System.out.println(name.length());
  }
}

This throws a NullPointerException. You tried to call a method on something that is null. This is probably the most common exception in Java. You will see it a lot.

The throws Keyword

Sometimes you do not want to handle an exception in the current method. You want to send it up to whoever called your method. Use the throws keyword.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
  static void readFile() throws FileNotFoundException {
    File f = new File("data.txt");
    Scanner sc = new Scanner(f);
  }

  public static void main(String[] args) {
    try {
      readFile();
    } catch (FileNotFoundException e) {
      System.out.println("Caught it here");
    }
  }
}

The readFile() method says "I might throw a FileNotFoundException, and I am not handling it โ€” you handle it." The throws declaration is like a warning label on the method.

๐Ÿงช Quick Quiz

Which of these is a checked exception in Java?