Rewrite Java try-catch with Optional

Introduction

When handling exceptions, try-catch syntax can be used, but scala.util.Try can be used for functional implementation.

In Java, the Try class cannot be used, but if you are not interested in the exception contents, you can use the Optional class. So, in this article, I'll show you how to convert an exception-based API to an Optional-based API in Java.

The target audience for this article is:

--People who have mastered Scala --People who are not familiar with Java

How to convert an exception-based API to an Optional-based API

It hides try-catch in the method and provides an Optional-based interface for the client.

    //Method to get time from Web API
    public static Optional<String> getTime() {
        try {
            //Set the connection destination URL and connection method.
            URL url = new URL("http://api.aoikujira.com/time/get.php");
            ......
            ......
            return Optional.of(time.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Optional.empty();
    }

Sample program

The program that acquires the current time from the Web API and displays it has been implemented in the following two ways.

--Exception base --Optional base

Exception-based programs

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        System.out.println(getTime());
    }

    //Method to get time from Web API
    private static String getTime() {
        try {
            //Set the connection destination URL and connection method.
            URL url = new URL("http://api.aoikujira.com/time/get.php");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("GET");
            http.connect();

            //Read the character string from the connection destination.
            BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
            StringBuilder time = new StringBuilder();
            String line = "";
            while((line = reader.readLine()) != null)
                time.append(line);

            return time.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            reader.close();
        }

        return "";
    }
}

Optional based program

Rewritten so that the getTime () method returns an Optional type. From the main routine (main method), the getTime () method looks like an Optional-based interface.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        System.out.println(getTime().orElse(""));
    }

    //Method to get time from Web API
    private static Optional<String> getTime() {
        try {
            //Set the connection destination URL and connection method.
            URL url = new URL("http://api.aoikujira.com/time/get.php");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestMethod("GET");
            http.connect();

            //Read the character string from the connection destination.
            BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
            StringBuilder time = new StringBuilder();
            String line = "";
            while((line = reader.readLine()) != null)
                time.append(line);
            reader.close();

            return Optional.of(time.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            reader.close();
        }

        return Optional.empty();
    }
}

in conclusion

If there is a smarter way, please comment.

Recommended Posts

Rewrite Java try-catch with Optional
Compare Java 8 Optional with Swift
Java Optional type
Studying Java 8 (Optional)
24 hours struggling with Android development, Java Optional
[Java] Optional memorandum
Java 9 Optional :: stream
Install java with Homebrew
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
View Java Optional Javadoc
Switch java with direnv
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Endian conversion with JAVA
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Java to play with Function
Try DB connection with Java
How to handle exceptions coolly with Java 8 Stream or Optional
How to use java Optional
Enable Java EE with NetBeans 9
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
[Java] About try-catch exception handling
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar
Sort strings functionally with java
Object-oriented (java) with Strike Gundam
[Java] How to use Optional ②
[Java] Content acquisition with HttpCliient
Java version control with jenv
Troubleshooting with Java Flight Recorder
Streamline Java testing with Spock
Connect to DB with Java
Connect to MySQL 8 with Java
Error when playing with java
Using Mapper with Java (Spring)
Java study memo 2 with Progate
Getting Started with Java Basics
Java8 to start now ~ Optional ~
Seasonal display with Java switch
Use SpatiaLite with Java / JDBC
[Java] How to use Optional ①
Study Java with Progate Note 1
HTML parsing with JAVA (scraping)
Run Java VM with WebAssembly
Screen transition with swing, java
Java unit tests with Mockito