为什么NumberFormatException是运行时?

编程入门 行业动态 更新时间:2024-10-23 10:20:10
本文介绍了为什么NumberFormatException是运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

运行时异常表示破损的合同(如NPE),如果代码没有错误,则不应抛出。它总是指示代码中的错误(与断言相同,但断言是内部类错误,而运行时是针对类的客户端错误)。

运行时异常不应该被捕获。 p>

另一方面,检查的异常是签名的一部分,应该被捕获和处理。它们可能表示用户输入错误或外部资源问题(例如 IOException )。

为什么 NumberFormatException 是运行时?

解决方案

首先,谁告诉过你

不应该捕获运行时异常

不太了解Java。不要听他们 - 他们错了。

NumberFormatException是一个运行时异常:未选中的异常是因为它们指示了一个编程错误。可以在调用 .String%29rel =nofollow> Integer.parseInt() (例如)String 有效整数,例如这里只是一种方式:

if(str.matches(^ \\d {1,8} $) { int myInt = Integer.parseInt(str); //永远不会抛出NumberFormatException }

因此,可以将其视为编程错误,程序员首先选择不。

如果你不会对要解析的字符串的完整性/质量有信心,很容易察觉:

try { //解析你的字符串} catch(NumberFormatException e){ // do something about it }

使其成为运行时的另一个原因是它不会使代码混淆,潜在的不必要的 try / catch 块如果你有信心你不会得到一个,例如,如果完全信任String数据的来源。

Runtime exceptions indicate broken contract (like NPE) and should never be thrown if code has no errors. It always indicates error in code (same as asserts but asserts are for internal class errors while Runtime are for class's client errors).

Runtime exceptions should never be catched.

Checked exceptions, on the other hand, are part of signature and should be catched and processed. They may indicate user input errors or external resource troubles (like IOException).

With all of it I can't get why NumberFormatException is runtime?

解决方案

Firstly, whoever told you

Runtime exceptions should never be caught

doesn't know much about Java. Don't listen to them - they are wrong.

NumberFormatException being a runtime exception: Unchecked exceptions are chosen because they indicate a programming error. It is possible to know before calling Integer.parseInt() (for example) that a String is a valid integer number, e.g. here's just one way:

if (str.matches("^\\d{1,8}$") { int myInt = Integer.parseInt(str); // will never throw NumberFormatException }

Therefore, it can be considered a programming error to ever get one - the programmer chose to not check first.

If you are not confident about the integrity/quality of the String you are about to parse, it's easy to catch:

try { // parse your string } catch (NumberFormatException e) { // do something about it }

The other reason to make it a runtime is that it doesn't clutter the code with potentially unnecessary try/catch blocks, if you are confident that you won't get one, e.g. if to totally trust the source of the String data.

更多推荐

为什么NumberFormatException是运行时?

本文发布于:2023-10-31 04:57:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NumberFormatException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!