Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. Lambda

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:

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:

@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:

@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.

PreviousStream APINextOptional in Functional Programming

Last updated 1 year ago