What are exceptions in Java and how are they handled?

What Are Exceptions in Java?

Exceptions in Java are events that occur during the execution of a program that disrupt the normal flow of instructions. They are objects that represent error conditions or unexpected behavior in a program.

Types of Exceptions

  1. Checked Exceptions:
    • These are exceptions that are checked at compile-time.
    • The compiler ensures that they are either handled using a try-catch block or declared in the method signature using the throws keyword.
    • Examples: IOException, SQLException.
  2. Unchecked Exceptions:
    • These are exceptions that occur at runtime and are not checked at compile-time.
    • They are subclasses of RuntimeException.
    • Examples: NullPointerException, ArrayIndexOutOfBoundsException.
  3. Errors:
    • These are serious issues that are usually beyond the control of the application.
    • They indicate problems with the JVM, such as memory leaks.
    • Examples: OutOfMemoryError, StackOverflowError.

How Are Exceptions Handled?

Java provides a robust mechanism to handle exceptions through the use of try, catch, finally, and throw keywords.

Exception Handling Syntax

try-catch Block

try: Code that might throw an exception is placed inside a try block.
catch: Code to handle the exception is placed inside a catch block.

Syntax
try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}

Multiple Catch Blocks

Multiple catch blocks can be used to handle different types of exceptions.

Syntax
try {
    // Code that may throw multiple exceptions
} catch (IOException e) {
    // Handle IOException
} catch (SQLException e) {
    // Handle SQLException
}

finally Block

A finally block contains code that is always executed, whether an exception is thrown or not. It is typically used for resource cleanup.

Syntax
try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code to execute regardless of an exception
}

throw Keyword

The throw keyword is used to explicitly throw an exception.

Syntax
public void myMethod() throws IOException {
    throw new IOException("Exception message");
}

throws Keyword

The throws keyword is used in a method signature to declare that the method can throw specified exceptions.

Syntax
public void myMethod() throws IOException, SQLException {
    // Method code
}

Example of Exception Handling:

import java.io.*;

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("test.txt");
            BufferedReader fileInput = new BufferedReader(file);
            
            // Reading first line of file
            System.out.println(fileInput.readLine());
            
            fileInput.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("Error reading file");
        } finally {
            System.out.println("Execution finished");
        }
    }
}

Summary

  • Checked Exceptions: Must be caught or declared.
  • Unchecked Exceptions: Runtime exceptions not checked at compile-time.
  • Errors: Serious issues beyond application control.
  • Handling Mechanisms: try, catch, finally, throw, throws.

More Information about Exceptions, Exception Handling and Errors: https://codevisionz.com/courses/java-errors-exception-handling/