CodeGym /Courses /JAVA 25 SELF /Exceptions as part of the API and try-with-resources

Exceptions as part of the API and try-with-resources

JAVA 25 SELF
Level 24, Lesson 4
Available

1. Exceptions as part of the API

Why are exceptions part of a method’s “contract”?

When you write a method, you define not only its parameters and return value, but also which exceptions it can throw. This is part of the “contract” between your method and its callers. If a method can throw an exception, everyone who calls it should know that — so they can handle the error correctly (or at least not be surprised when the program suddenly terminates with an error).

Example:

public void readFile(String filename) throws IOException {
    // ... file reading
}

Here it’s explicitly stated that the method can throw IOException. This signals to the method’s user: “Be prepared to handle a file read error!”

Documenting exceptions: the @throws tag in Javadoc

To help other developers understand which exceptions your method can throw, use the @throws (or @exception) tag in Javadoc.

Example:

/**
 * Reads the contents of a file.
 *
 * @param filename file name
 * @return file contents as a string
 * @throws IOException if a file read error occurs
 */
public String readFile(String filename) throws IOException {
    // ...
}

Why do this?

  • Helps other developers understand which errors they need to handle.
  • IDEs and documentation generators (e.g., Javadoc) show these exceptions right in tooltips.
  • Improves code reliability and predictability.

Checked and unchecked exceptions in the API

Checked exceptions (subclasses of Exception, but not RuntimeException) are part of a method’s contract. You must either handle them or explicitly rethrow them (throws).

Unchecked exceptions (RuntimeException and its subclasses) usually signal programming errors (for example, NullPointerException, IllegalArgumentException). You don’t have to declare them in the signature, but if your method can throw such an error (e.g., for invalid arguments), you should still describe it in the Javadoc.

Example:

/**
 * Divides a by b.
 * @param a dividend
 * @param b divisor
 * @return the result of the division
 * @throws IllegalArgumentException if b == 0
 */
public int divide(int a, int b) {
    if (b == 0) throw new IllegalArgumentException("Divisor cannot be zero");
    return a / b;
}

Exceptions and API design

  • Think about your method’s user: which errors can and should they handle? Which ones are bugs, and which are “working” situations?
  • Don’t overuse checked exceptions: if the error is a bug (for example, an invalid argument), it’s better to throw an unchecked exception.
  • Document all exceptions that can be thrown “upward”.

2. The try-with-resources construct

Problem: how to close resources safely?

In many tasks you have to work with resources that must be closed after use: files, network connections, databases, etc. If you forget to close a resource, you can end up with a memory leak, a file lock, or other issues.

Before:

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("data.txt"));
    String line = reader.readLine();
    // ...
} catch (IOException e) {
    // error handling
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            // error handling when closing
        }
    }
}

Lots of code, easy to make a mistake, and you might forget to close the resource.

Solution: try-with-resources

Since Java 7 there’s the try-with-resources construct, which automatically closes all resources, even if an exception is thrown inside the block.

Syntax:

try (ResourceType resource = new ResourceType(...)) {
    // work with the resource
} catch (ExceptionType e) {
    // error handling
}

Example:

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
    String line = reader.readLine();
    System.out.println(line);
} catch (IOException e) {
    System.out.println("Error reading file: " + e.getMessage());
}
// reader.close() will be called automatically!

How does it work?

  • In the parentheses after try, you declare the resources that need to be closed.
  • After exiting the try block (even if an exception occurs!), the close() method is called for each resource.
  • This works only for resources that implement the AutoCloseable interface (or its ancestor Closeable).

The AutoCloseable interface:

public interface AutoCloseable {
    void close() throws Exception;
}

All standard Java resources (files, streams, DB connections) implement this interface.

You can declare multiple resources

try (
    BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
    BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))
) {
    String line;
    while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.newLine();
    }
}

Both resources will be closed automatically, even if an exception occurs.

Benefits of try-with-resources

  • Safety: resources are always closed, even on errors.
  • Conciseness: less code, fewer chances to make a mistake.
  • Readability: it’s immediately clear which resources are used and when they are closed.

3. Practice: write safe code with try-with-resources

Example: reading a file

public static void printFirstLine(String filename) {
    try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
        String line = reader.readLine();
        System.out.println("First line: " + line);
    } catch (IOException e) {
        System.out.println("Error: " + e.getMessage());
    }
}

Example: writing to a file

public static void writeToFile(String filename, String text) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
        writer.write(text);
    } catch (IOException e) {
        System.out.println("Error while writing: " + e.getMessage());
    }
}

Example: a custom resource

If you’re writing your own class that needs to be closed, just implement AutoCloseable:

public class MyResource implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("Resource closed!");
    }
}

Now you can use it in try-with-resources:

try (MyResource res = new MyResource()) {
    // work with the resource
} 

4. Common mistakes and best practices

Error #1: forgot to close a resource (without try-with-resources).
If you don’t use try-with-resources, it’s easy to forget to close a file or stream — this leads to resource leaks.

Error #2: trying to use try-with-resources with an object that doesn’t implement AutoCloseable.
If your class doesn’t implement this interface, the compiler won’t allow you to use it in try-with-resources.

Error #3: not documenting exceptions in the API.
If your method can throw an exception, be sure to specify this in the signature (throws) and in Javadoc (@throws). This helps others use your code correctly.

Error #4: catching Exception instead of specific errors.
It’s better to catch only those exceptions you actually expect and can handle.

1
Task
JAVA 25 SELF, level 24, lesson 4
Locked
News Aggregator: Automatic Article Title Reading
News Aggregator: Automatic Article Title Reading
1
Task
JAVA 25 SELF, level 24, lesson 4
Locked
Magic artifact: Automatic shutdown
Magic artifact: Automatic shutdown
1
Task
JAVA 25 SELF, level 24, lesson 4
Locked
Science Lab: Documenting Potential Data Failures
Science Lab: Documenting Potential Data Failures
1
Task
JAVA 25 SELF, level 24, lesson 4
Locked
Digital Archivist: Secure Copying of Ancient Manuscripts
Digital Archivist: Secure Copying of Ancient Manuscripts
1
Survey/quiz
Exception hierarchy, level 24, lesson 4
Unavailable
Exception hierarchy
Advanced work with exceptions
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION