大多数情况下,如果调用者可以恢复异常,则应使用已检查的异常。如果不是,则应使用运行时异常。运行时异常表示可以通过检查某些先决条件(例如数组边界和空性检查)来防止的编程错误。
在下面的方法中,IllegalArgumentException
是一个RuntimeException
,它的用法表示编程错误。通常可以通过检查前提条件来避免编程错误。所以这是基于这个技巧的一个不好的例子。可以通过检查先决条件来避免异常,即这里的“hasNext()
”方法。
/** * Convert a tag string into a tag map. * * @param tagString a space-delimited string of key-value pairs. For example, {@code "key1=value1 key_n=value_n"} * @return a tag {@link Map} * @throws IllegalArgumentException if the tag string is corrupted. */ public static MapparseTags(final String tagString) throws IllegalArgumentException { // delimit by whitespace or '=' Scanner scanner = new Scanner(tagString).useDelimiter("\\s+|="); Map tagMap = new HashMap (); try { while (scanner.hasNext()) { String tagName = scanner.next(); String tagValue = scanner.next(); tagMap.put(tagName, tagValue); } } catch (NoSuchElementException e) { // The tag string is corrupted. throw new IllegalArgumentException("Invalid tag string '" + tagString + "'"); } finally { scanner.close(); } return tagMap; }
The above is the detailed content of How to distinguish recoverable conditions and programming errors in Java and use checked exceptions and runtime exceptions to handle them?. For more information, please follow other related articles on the PHP Chinese website!