Skip to main content

2024-07-03

One-liner

Memory is the root of pain. — "Kung Fu Hustle" · acheing


ExceptionHandler & try...catch

Today while writing code, I encountered a scenario where I needed to handle exceptions. With an existing ExceptionHandler, can we still catch exceptions using try...catch in the code?

Yes, we can catch exceptions

Key Point

A global ExceptionHandler is mainly for handling exceptions that are not caught within the method.

  1. Method a throws BussinessException:

    public void a() throws BussinessException {
    // Business logic that might throw BussinessException
    throw new BussinessException("Business exception message");
    }
  2. Method b catches the Exception:

    public void b() {
    try {
    a(); // Call method a
    } catch (Exception e) {
    // Exception caught
    System.out.println("Caught exception: " + e.getMessage());
    }
    }

In this example, when b method is called, a method throws a BussinessException. Since b method uses a try-catch block to catch Exception, the BussinessException will be caught because BussinessException is a subclass of Exception.

public void b() {
try {
a(); // Call method a
} catch (BussinessException e) {
// Specifically catch BussinessException
System.out.println("Caught business exception: " + e.getMessage());
} catch (Exception e) {
// Catch all subclasses of Exception
System.out.println("Caught exception: " + e.getMessage());
}
}

Doing so allows for more granular exception handling, catching specific exception types first, and then all other exceptions.

Summary: In method b, we can catch the BussinessException thrown by method a using a try-catch block. Even with a global ExceptionHandler for handling BussinessException, it does not affect the ability to catch exceptions within method b. The global ExceptionHandler is primarily for exceptions not caught within the method.

Optional is a container class introduced in Java 8 to handle potential null values, thus avoiding NullPointerException. It provides a more elegant way to deal with potentially null values. Below is a detailed introduction to the Optional class:

Optional

Having rarely used the Optional class before, I decided to document it.

Core Features

  1. Creating Optional objects: The Optional class provides several static methods to create Optional objects:

    • Optional.of(T value): Creates an Optional object containing the specified value, throwing NullPointerException if the value is null.
    • Optional.ofNullable(T value): Creates an Optional object that may contain a null value.
    • Optional.empty(): Creates an empty Optional object.
  2. Checking if a value is present:

    • isPresent(): Returns true if a value is present, otherwise returns false.
    • ifPresent(Consumer<? super T> consumer): If a value is present, performs the given action with the value, otherwise does nothing.
  3. Retrieving the value:

    • get(): Returns the contained value if present, otherwise throws NoSuchElementException.
    • orElse(T other): Returns the contained value if present, otherwise returns the specified default value.
    • orElseGet(Supplier<? extends T> other): Returns the contained value if present, otherwise returns the value produced by the specified Supplier.
    • orElseThrow(Supplier<? extends X> exceptionSupplier): Returns the contained value if present, otherwise throws the exception produced by the specified Supplier.
  4. Filtering and transforming:

    • filter(Predicate<? super T> predicate): If a value is present and matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.
    • map(Function<? super T,? extends U> mapper): If a value is present, applies the provided function to it and returns an Optional describing the result, otherwise returns an empty Optional.
    • flatMap(Function<? super T,Optional<U>> mapper): Similar to map, but the mapping function must return an Optional.

Example Code

import java.util.Optional;

public class OptionalExample {
public static void main(String[] args) {
// Create an Optional object
Optional<String> optional = Optional.of("Hello");

// Check if the value is present
if (optional.isPresent()) {
System.out.println("Value is present: " + optional.get());
} else {
System.out.println("Value is not present");
}

// Use orElse to provide a default value
String value = optional.orElse("Default Value");
System.out.println("Value: " + value);

// Use map to transform the value
Optional<String> upperCase = optional.map(String::toUpperCase);
upperCase.ifPresent(System.out::println);

// Use flatMap
Optional<String> flatMapped = optional.flatMap(v -> Optional.of(v + " World"));
flatMapped.ifPresent(System.out::println);
}
}

References

The Optional class provides an elegant way to handle potentially null values, avoiding traditional null checks and enhancing code readability and safety.