Sobes.tech
Junior

What is an exception in Java?

sobes.tech AI

Answer from AI

An exception is an event that disrupts the normal flow of a program's execution. It represents an error or an unforeseen situation.

In Java, exceptions are represented by a hierarchy of classes starting with Throwable. It is divided into:

  • Error: Represents serious problems that are usually unrecoverable (e.g., OutOfMemoryError).
  • Exception: Represents conditions that the program may attempt to recover from. It is divided into:
    • Checked Exceptions: Exceptions that must be handled or declared in the method signature. The compiler checks for their presence (e.g., IOException, FileNotFoundException).
    • Unchecked Exceptions (Runtime Exceptions): Exceptions that do not need to be handled or declared explicitly. They usually indicate errors in the program logic (e.g., NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException).

The exception handling mechanism includes:

  1. try: A block of code that may throw an exception.
  2. catch: A block that catches and handles a specific type of exception.
  3. finally: A block that always executes, regardless of whether an exception was thrown or not. It is used for resource cleanup.
  4. throw: Used to explicitly throw an exception.
  5. throws: Declared in the method signature to indicate that the method may throw a specific exception.

Example of exception handling:

// Example of handling a Checked Exception
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ExceptionHandlingExample {

    public static void main(String[] args) {
        try {
            readFile("nonexistent_file.txt");
        } catch (FileNotFoundException e) {
            // Handle the exception
            System.err.println("Error: file not found.");
            e.printStackTrace(); // Print exception information
        } finally {
            // This block will always execute
            System.out.println("Finished attempting to read the file.");
        }

        // Example of Unchecked Exception (ArithmeticException)
        try {
            int result = 10 / 0; // Attempt to divide by zero
        } catch (ArithmeticException e) {
            System.err.println("Division by zero error!");
        }
    }

    // Method that may throw a Checked Exception
    public static void readFile(String filename) throws FileNotFoundException {
        File file = new File(filename);
        Scanner scanner = new Scanner(file);
        // Reading the file...
        scanner.close();
    }
}
What is an exception in Java? — Java - sobes.tech