> For the complete documentation index, see [llms.txt](https://muhammad-tri-wibowo.gitbook.io/java-tutorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://muhammad-tri-wibowo.gitbook.io/java-tutorials/lambda/error-handling-in-lambda-expressions.md).

# Error Handling in Lambda Expressions

**Exception Handling in Lambda:**

Lambda expressions can handle exceptions internally using a `try-catch` block. However, this approach can lead to verbose code, especially for checked exceptions.

**Example of Exception Handling in Lambda:**

```java
import java.util.function.Consumer;

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        // Lambda with exception handling
        Consumer<String> printLength = input -> {
            try {
                int length = input.length();
                System.out.println("Length: " + length);
            } catch (NullPointerException e) {
                System.out.println("Input is null");
            }
        };

        // Test with null input
        printLength.accept(null); // Output: Input is null
    }
}
```

**Handling Checked Exceptions in Lambda:**

For checked exceptions, you can define a functional interface that throws the specific exception, allowing lambda expressions to throw checked exceptions.

**Example of Handling Checked Exceptions in Lambda:**

```java
@FunctionalInterface
interface CheckedFunction<T, R> {
    R apply(T t) throws Exception;
}

public class CheckedLambdaExample {
    public static void main(String[] args) {
        CheckedFunction<String, Integer> stringToInt = s -> {
            if (s == null) {
                throw new IllegalArgumentException("Input is null");
            }
            return Integer.parseInt(s);
        };

        try {
            int result = stringToInt.apply("123");
            System.out.println("Result: " + result); // Output: Result: 123
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
```

**Using Functional Interfaces for Exception Handling:**

You can create custom functional interfaces that handle specific exceptions, allowing lambda expressions to throw those exceptions.

**Example of Using Functional Interfaces for Exception Handling:**

```java
@FunctionalInterface
interface ThrowingConsumer<T> {
    void accept(T t) throws Exception;
}

public class CustomFunctionalInterfaceExample {
    public static void main(String[] args) {
        ThrowingConsumer<String> printLength = input -> {
            if (input == null) {
                throw new IllegalArgumentException("Input is null");
            }
            System.out.println("Length: " + input.length());
        };

        try {
            printLength.accept("Hello");
            printLength.accept(null); // Throws IllegalArgumentException
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
```

In this example, `ThrowingConsumer` is a functional interface that allows a lambda expression to throw an exception. The lambda expression inside `printLength.accept(null)` throws an `IllegalArgumentException`, which is caught in the `catch` block.

By using custom functional interfaces or existing functional interfaces with specific exceptions, you can handle exceptions in lambda expressions effectively, making your code more concise and readable while ensuring proper error handling.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://muhammad-tri-wibowo.gitbook.io/java-tutorials/lambda/error-handling-in-lambda-expressions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
