How can I handle an IOException which I know can never be thrown, in a safe and readable manner?

后端 未结 8 1834
生来不讨喜
生来不讨喜 2021-02-02 12:07

\"The major difference between a thing that might go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong go

8条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 13:12

    You can convert a checked exception to an unchecked by nestling it inside a RuntimException. If the exception is caught higher up in the stack and outputted using printStackTrace(), the stack for the original exception will be displayed as well.

    try {
        // code...
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
    

    This is a good solution, that you shouldn't hesitate to use in these situations.

提交回复
热议问题