Get the App
SLTechnology News&Howtos  ›  Development  › 

How java implements checking exceptions for recoverable conditions and using run-time exceptions for programming errors

Shulou Source: shulou.com Published: 2022-06-01 06:16:58 10月01日 Update

This article will explain in detail how java can check exceptions for recoverable conditions and use runtime exceptions for programming errors. The editor finds it very practical, so I share it with you for reference. I hope you can get something after reading this article.

Use check exceptions for recoverable conditions and run-time exceptions for programming errors

In most cases, if the caller can recover the exception, you should use the checked exception. If not, run-time exceptions should be used. Run-time exceptions represent programming errors that can be prevented by checking certain prerequisites, such as array boundaries and nullability checks.

In the following method, IllegalArgumentException is a RuntimeException, which is used to indicate a programming error. Programming errors can usually be avoided by checking prerequisites. So this is a bad example based on this technique. You can avoid exceptions by checking the prerequisites, that is, the "hasNext ()" method here.

/ * 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 } this is the end of the article on "how java can check exceptions for recoverable conditions and use runtime exceptions for programming errors". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Check conditions errors programming run can pass articles prerequisites methods more good practical bad examples content premises situations techniques arrays articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Information MariaDB Redmi macOS