Sobes.tech
Junior — Middle

How can exceptions be handled without using the standard request?

sobes.tech AI

Answer from AI

In Java, the standard way to handle exceptions is using try-catch blocks. If you want to handle an exception without using try-catch, you can use methods that handle exceptions internally, or apply functional interfaces with error handling.

For example, you can use a method with throws, which propagates the exception up the stack, or use Optional to handle potential errors without throwing exceptions.

Example with Optional:

import java.util.Optional;

public class Example {
    public static Optional<Integer> parseInt(String s) {
        try {
            return Optional.of(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    public static void main(String[] args) {
        Optional<Integer> number = parseInt("123a");
        number.ifPresentOrElse(
            n -> System.out.println("Parsed number: " + n),
            () -> System.out.println("Failed to parse number")
        );
    }
}

Thus, the exception is not thrown outward but handled inside the method, and the calling code works with the result without try-catch.

How can exceptions be handled without using the… - sobes.tech