为什么NumberFormatException是运行时? [英] Why NumberFormatException is runtime?

查看:221
本文介绍了为什么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是运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆