Home> Java> javaTutorial> body text

How to distinguish recoverable conditions and programming errors in Java and use checked exceptions and runtime exceptions to handle them?

WBOY
Release: 2023-05-06 22:13:08
forward
1108 people have browsed it

对可恢复条件使用检查异常,对编程错误使用运行时异常

大多数情况下,如果调用者可以恢复异常,则应使用已检查的异常。如果不是,则应使用运行时异常。运行时异常表示可以通过检查某些先决条件(例如数组边界和空性检查)来防止的编程错误。

在下面的方法中,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 Map parseTags(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; }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!