2024-07-03
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
A global ExceptionHandler
is mainly for handling exceptions that are not caught within the method.
-
Method
a
throws BussinessException:public void a() throws BussinessException {
// Business logic that might throw BussinessException
throw new BussinessException("Business exception message");
} -
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
-
Creating
Optional
objects: TheOptional
class provides several static methods to createOptional
objects:Optional.of(T value)
: Creates anOptional
object containing the specified value, throwingNullPointerException
if the value isnull
.Optional.ofNullable(T value)
: Creates anOptional
object that may contain anull
value.Optional.empty()
: Creates an emptyOptional
object.
-
Checking if a value is present:
isPresent()
: Returnstrue
if a value is present, otherwise returnsfalse
.ifPresent(Consumer<? super T> consumer)
: If a value is present, performs the given action with the value, otherwise does nothing.
-
Retrieving the value:
get()
: Returns the contained value if present, otherwise throwsNoSuchElementException
.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 specifiedSupplier
.orElseThrow(Supplier<? extends X> exceptionSupplier)
: Returns the contained value if present, otherwise throws the exception produced by the specifiedSupplier
.
-
Filtering and transforming:
filter(Predicate<? super T> predicate)
: If a value is present and matches the given predicate, returns anOptional
describing the value, otherwise returns an emptyOptional
.map(Function<? super T,? extends U> mapper)
: If a value is present, applies the provided function to it and returns anOptional
describing the result, otherwise returns an emptyOptional
.flatMap(Function<? super T,Optional<U>> mapper)
: Similar tomap
, but the mapping function must return anOptional
.
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.