Would you ever NOT catch an exception, or throw an exception that won't be caught?

前端 未结 14 848
感情败类
感情败类 2021-01-03 09:49

I\'ve dealt with instances where I would throw/rethrow an exception knowing that the code surrounding it would catch the specific exception. But is there any time you would

14条回答
  •  醉梦人生
    2021-01-03 10:04

    Sure. For example, if you're trying to load some bytes into a string in Java:

    try {
      String myString = new String(byteArray, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      // Platform doesn't support UTF-8?  What is this, 1991?
      throw new RuntimeExceptione(e);
    }
    

    In this case, there is no graceful degradation, the platform simply can't support the operation desired. You can check for this condition at initialization all you want, but the constructor for String still throws this exception, and you have to deal with it. Either that, or use Charset.forName() :)

提交回复
热议问题