How to close std-streams from java.lang.Process appropriate?

后端 未结 3 868
星月不相逢
星月不相逢 2021-01-01 06:00

This question is about java.lang.Process and its handling of stdin, stdout and stderr.

We have a class in our project that is an extension to org.

3条回答
  •  长情又很酷
    2021-01-01 06:53

    An attempt at simplifying your code:

    public static void close(@Nullable Process process) throws IOException
    {
        if(process == null) { return; }
    
        try
        {
            close(process.getOutputStream());
            close(process.getInputStream());
            close(process.getErrorStream());
    
            if(process.waitFor() != 0)
            {
                process.destroy();
            }
        }
        catch(InterruptedException e)
        {
            process.destroy();
        }
        catch (RuntimeException e)
        {
            throw (e instanceof IOException) ? e : new IOException(e);
        }
    }
    

    By catching Throwable I assume you wish to catch all unchecked exceptions. That is either a derivative of RuntimeException or Error. However Error should never be catched, so I have replaced Throwable with RuntimeException.

    (It is still not a good idea to catch all RuntimeExceptions.)

提交回复
热议问题