最常见的检查和未检查 Java 异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1263128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 07:33:46  来源:igfitidea点击:

Most common checked and unchecked Java Exceptions?

javaexception

提问by Brian Johnson

As far as I understand, there is no way to find out which exceptions a method throws without looking up the API docs one-by-one.

据我了解,如果不一一查找 API 文档,就无法找出方法抛出哪些异常。

Since that is no option, I'd like to reverse the research and ask you which are the most common Exceptions and RuntimeExceptions you've come across when dealing with:

由于这是不可能的,我想扭转研究并询问您在处理时遇到的最常见的异常和运行时异常:

  • Casting
  • Arrays
  • Vector, ArrayList, HashMap, etc.
  • IO (File class, streams, filters, ...)
  • Object Serialization
  • Threads (wait(), sleep(), etc.)
  • or anything else that is considered "basic Java"
  • 铸件
  • 数组
  • Vector、ArrayList、HashMap等。
  • IO(文件类、流、过滤器等)
  • 对象序列化
  • 线程(wait()、sleep() 等)
  • 或任何其他被认为是“基本 Java”的东西

I realize that this might be subjective and boring but it is for a class test and I really don't know better.

我意识到这可能是主观和无聊的,但它是为了课堂测试,我真的不知道。

采纳答案by Platinum Azure

Assume the below are java.langunless I specify otherwise:

java.lang除非我另有说明,否则假设如下:

  • Casting: ClassCastException
  • Arrays: ArrayIndexOutOfBoundsException, NullPointerException
  • Collections: NullPointerException, ClassCastException (if you're not using autoboxing and you screw it up)
  • IO: java.io.IOException, java.io.FileNotFoundException, java.io.EOFException
  • Serialization: java.io.ObjectStreamException (AND ITS SUBCLASSES, which I'm too lazy to enumerate)
  • Threads: InterruptedException, SecurityException, IllegalThreadStateException
  • Potentially common to all situations: NullPointerException, IllegalArgumentException
  • 铸造:ClassCastException
  • 数组:ArrayIndexOutOfBoundsException、NullPointerException
  • 集合:NullPointerException、ClassCastException(如果你没有使用自动装箱并且你搞砸了)
  • IO: java.io.IOException, java.io.FileNotFoundException, java.io.EOFException
  • 序列化:java.io.ObjectStreamException(及其子类,我懒得一一列举)
  • 线程:InterruptedException、SecurityException、IllegalThreadStateException
  • 可能适用于所有情况:NullPointerException、IllegalArgumentException

You would do well to look at Java site's Package Summary pages.Here's one: http://java.sun.com/j2se/1.4.2/docs/api/java/io/package-summary.html

您最好查看 Java 站点的 Package Summary 页面。这是一个:http: //java.sun.com/j2se/1.4.2/docs/api/java/io/package-summary.html

回答by Gandalf

NullPointerException

空指针异常

回答by Bill K

Checked exceptions are easy, your editor should display the javadocs when you hover/complete the method name.

检查异常很容易,当您悬停/完成方法名称时,您的编辑器应该显示 javadoc。

Unchecked are generally actual errors and aren't even in the javadocs more often than not. I guess the most common might be IllegalArgumentException, any method that has any possible combination of parameters that is invalid should throw it.

未经检查的通常是实际错误,甚至在 javadoc 中也不经常出现。我想最常见的可能是 IllegalArgumentException,任何具有任何可能无效参数组合的方法都应该抛出它。

回答by djna

How about looking for subclasses of java.lang.exception, for example here

如何寻找java.lang.exception的子类,例如here

Personally I use 2 checked exceptions of my own TransientException for cases when a retry might work. And InvalidRequestException for validation errors.

对于重试可能有效的情况,我个人使用我自己的 TransientException 的 2 个检查异常。和 InvalidRequestException 用于验证错误。

回答by firstthumb

NumberFormatException

数字格式异常

回答by Stephen C

As Bill K says. Checked exceptions are easy. If your IDE/program editor doesn't give you an quick way to see method javadocs or signatures you need to throw it away. Seriously.

正如比尔 K 所说。检查异常很容易。如果您的 IDE/程序编辑器没有为您提供查看方法 javadoc 或签名的快速方法,您需要将其丢弃。严重地。

Unchecked exceptions are a different kettle of fish. But I think the best strategy with unchecked exceptions is to not try to catch them. Instead, you write you code so that it avoids throwing them in the first place. For example;

未经检查的异常是另一种鱼。但我认为处理未检查异常的最佳策略是不要试图捕捉它们。相反,您编写代码是为了避免首先抛出它们。例如;

// ... not sure if 'obj' is null
if (obj != null) {
    obj.someMethod();
}
// ... not sure if 'obj' has the right type
if (obj instanceof Foo) {
    Foo foo = (Foo) obj;
}
// ... not sure if 'i' is in range
if (i >= 0 && i < array.length) {
    .... = array[i];
}

Here's why I recommend this:

这就是我推荐这个的原因:

  • A guard test is orders of magnitudemore efficient than throwing and catching an exception.
  • A guard test is more readable ... less lines of code.
  • If you catch an unchecked exception, you can never be sure that it happened for the reasons you think it did; for example:
  • 守卫测试比抛出和捕获异常效率高几个数量级
  • 守卫测试更具可读性……更少的代码行。
  • 如果你捕捉到一个未经检查的异常,你永远无法确定它发生的原因是你认为的那样;例如:
    // obj might be null ...
    try {
        obj.doSomething();
    } catch (NullPointerException ex) {
        System.err.println("obj was null");  // WRONG!!!
        // the NPE could have happen inside doSomething()
    }
  • If an unchecked exception is caused by a bug, you DO want a stacktrace and (depending on the application) you MAY NOT want to recover.
  • 如果未经检查的异常是由错误引起的,您确实需要堆栈跟踪并且(取决于应用程序)您可能不想恢复。

Obviously, you only include these "guard" checks where your understanding of the code tells you that they are necessary! So, for example if you knowthat 'obj' ought to be non-null and 'i' ought to be in range, it is a good idea to leave the checks out. If you leave out one test too many, you'll get an exception ... but that's good because you can then use the stacktrace to figure out why your understanding of the code was wrong, and maybe fix the underlying bug.

显然,您只在您对代码的理解告诉您它们是必要的情况下才包含这些“守卫”检查!因此,例如,如果您知道'obj' 应该是非 null 并且 'i' 应该在范围内,那么最好不要进行检查。如果您遗漏了太多的测试,您会得到一个异常……但这很好,因为您可以使用堆栈跟踪找出您对代码的理解错误的原因,并可能修复潜在的错误。

回答by ADITYA VALLURU

java.lang:

java.lang:

  1. ArithmeticException
  2. ArrayIndexOutOfBoundsException
  3. ClassCastException
  4. ClassNotFoundException
  5. CloneNotSupportedException
  6. IllegalArgumentExcepion
  7. IllegalMonitorStateException
  8. IllegalThreadStateException
  9. IndexOutOfBoundsException
  10. InterruptedException
  11. NullPointerException
  12. NumberFormatedException
  1. 算术异常
  2. ArrayIndexOutOfBoundsException
  3. 类转换异常
  4. 类未找到异常
  5. 克隆不支持异常
  6. 非法参数异常
  7. 非法监视器状态异常
  8. 非法线程状态异常
  9. 索引出界异常
  10. 中断异常
  11. 空指针异常
  12. 数字格式异常

java.util:

java.util:

  1. ConcurrentModificationException
  1. 并发修改异常

java.io :

.io :

  1. EOFException
  2. FileNotFoundException
  3. IOException
  4. NotSerializableException
  1. EOF异常
  2. 文件未找到异常
  3. IO异常
  4. 不可序列化异常

回答by Warren Dew

  • Casting - ClassCastException

  • Arrays - ArrayIndexOutOfBoundsException

  • Vector, ArrayList, HashMap, etc. - I rarely see exceptions when working with Java collections, but very occasionally ConcurrentModificationException

  • IO (File class, streams, filters, …) - FileNotFoundException

  • Object Serialization - ClassNotFoundException

  • Threads (wait(), sleep(), etc.) - In my experience, usually threading problems manifest themselves in random ways that aren't exception specific. Having to deal with InterruptedException occupies a lot of time, though I haven't seen the exception actually thrown much.

  • or anything else that is considered "basic Java" - by far the most common exception in my experience is NullPointerException.

  • 铸造 - ClassCastException

  • 数组 - ArrayIndexOutOfBoundsException

  • Vector、ArrayList、HashMap 等 - 我在处理 Java 集合时很少看到异常,但偶尔会看到 ConcurrentModificationException

  • IO(文件类、流、过滤器等)- FileNotFoundException

  • 对象序列化 - ClassNotFoundException

  • 线程(wait()、sleep() 等)——根据我的经验,线程问题通常以随机方式表现出来,而不是特定于异常的。不得不处理 InterruptedException 占用了很多时间,虽然我还没有看到实际抛出的异常。

  • 或任何其他被认为是“基本 Java”的东西——到目前为止,我的经验中最常见的异常是 NullPointerException。

回答by Praveen Kishor

Unchecked Exception List
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NullPointerException
NumberFormatException
AssertionError
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError

未经检查的异常列表
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NullPointerException
NumberFormatException
AssertionError
ExceptionInInitializerError
StackOverflowError
NoClassDefFoundError

Checked Exception List
Exception
IOException
FileNotFoundException
ParseException
ClassNotFoundException
CloneNotSupportedException
InstantiationException
InterruptedException
NoSuchMethodException
NoSuchFieldException

检查异常列表
异常
IOException
FileNotFoundException
ParseException
ClassNotFoundException
CloneNotSupportedException
InstantiationException
InterruptedException
NoSuchMethodException
NoSuchFieldException

回答by SOFe

I would like to contribute a list that groups by situation, which is probably more meaningful than grouping by packages or fields of programming.

我想提供一个按情况分组的列表,这可能比按包或编程领域分组更有意义。

Unexpected exceptions

意外异常

These are exceptions that should ideally never be thrown in production. You should fix them instead of catching them and stfu.

这些是理想情况下永远不应在生产中抛出的异常。你应该修复它们而不是捕捉它们和 stfu。

when you test newly written code (and sometimes unexpectedly seen by users)

当您测试新编写的代码时(有时用户会意外看到)

They should never happen again once you see them.

一旦你看到它们,它们就不应该再发生了。

  • AssertionError
    • congratulations, you are writing good code
    • you should be happy that you made this error, because less (errors) is more (bugs)
    • I hope you won't end up finding out that your code is correct and you accidentally inverted your assertion
  • NullPointerException
    • where are your @NotNulls?
    • did you check before using the return value from Map.get()?
  • ArrayIndexOutOfBoundsException
    • do you check before using List.get()?
    • I hope you know well enough that Java isn't JavaScript, arrays are fixed-sized and you can't just array[array.length] = newElement
  • ClassCastException
    • too much generics is bad for your brain cells; consider moving to golang!
  • IllegalArgumentException
    • this could sometimes mean "read the fishing docs"
  • 断言错误
    • 恭喜你,你写的代码很好
    • 你应该很高兴你犯了这个错误,因为少(错误)就是多(错误)
    • 我希望你最终不会发现你的代码是正确的,并且你不小心颠倒了你的断言
  • 空指针异常
    • 你在哪里@NotNull
    • 你在使用返回值之前检查过Map.get()吗?
  • ArrayIndexOutOfBoundsException
    • 你在使用前检查List.get()吗?
    • 我希望你足够了解 Java 不是 JavaScript,数组是固定大小的,你不能只是 array[array.length] = newElement
  • 类转换异常
    • 太多的仿制药对你的脑细胞有害;考虑搬到golang!
  • 非法参数异常
    • 这有时可能意味着“阅读钓鱼文档”

And less likely to see,

而且不太可能看到,

  • IllegalMonitorStateException
    • yes, having to synchronizedsucks, but it's like this in most languages
  • CloneNotSupportedException
    • hey, just don't use clone(). aren't copy constructors cool?
  • 非法监视器状态异常
    • 是的,synchronized这很糟糕,但在大多数语言中都是这样
  • 克隆不支持异常
    • 嘿,只是不要使用 clone()。复制构造函数是不是很酷?

And then you get more NullPointerException.

然后你会得到更多的 NullPointerException。

And then... Still NullPointerException? That @NotNullannotation is rubbish!

然后……还是 NullPointerException?那个@NotNull注释是垃圾!

when you test newly written code for the 100th time

当您第 100 次测试新编写的代码时

Exceptions that happen due to race conditions or rare probability. You should buy a lottery if you see them the first 10 times you run your code.

由于竞争条件或罕见概率而发生的异常。如果您在运行代码的前 10 次看到它们,则应该购买彩票。

  • ConcurrentModificationException
    • ?your synchronizedis where
  • IllegalStateException
  • StackOverflowError (not Exception)
    • have you tried tail recursion?
  • 并发修改异常
    • ?你synchronized在哪里
  • 非法状态异常
  • StackOverflowError(不是异常)
    • 你试过尾递归吗?

during compilation, deployment, etc.

在编译、部署等过程中。

They usually happen when you messed up the dependencies, used wrong versions of libraries, etc.

它们通常发生在您弄乱了依赖项、使用了错误版本的库等时。

  • LinkageError
  • NoClassDefFoundError
  • java.lang.XxxNotFoundException, java.lang.NoSuchXxxException (classes, methods, etc.)
    • not reflections please
  • 联动错误
  • NoClassDefFoundError
  • java.lang.XxxNotFoundException、java.lang.NoSuchXxxException(类、方法等)
    • 请不要反思

when you are too lazy

当你太懒的时候

and when you are using @lombok.SneakyThrowsor equivalent

当您使用@lombok.SneakyThrows或等效时

  • RuntimeException
  • ? extends RuntimeException
  • 运行时异常
  • ? 扩展运行时异常

Expected exceptions

预期异常

If they are not caught, this probably means you are too lazy as well. You can't prevent them from throwing; you just have to catch them.

如果他们没有被抓住,这可能意味着你也太懒了。你无法阻止他们投掷;你只需要抓住他们。

high likeliness

高可能性

These exceptions have high likeliness to happen, and should always be handled specifically (i.e. you should actually handle them instead of just outputting the error)

这些异常发生的可能性很高,并且应该始终进行专门处理(即您应该实际处理它们而不是仅仅输出错误)

  • NumberFormatException
    • I never understand why this exception extends RuntimeException.
  • 数字格式异常
    • 我一直不明白为什么这个异常会扩展 RuntimeException。

medium likeliness

中等可能性

These exceptions sometimes happen due to invalid user input (but you should really validate them, so I classify these as "unexpected exceptions"), and sometimes happen due to system constraints that might not be reproducible when (non-stress) testing.

这些异常有时是由于无效的用户输入而发生的(但你应该真正验证它们,所以我将这些归类为“意外异常”),有时是由于在(非压力)测试时可能无法重现的系统限制而发生的。

  • IOException and other java.io.XxxException
  • SecurityException
  • StackOverflowException
    • unfortunately, going to StackOverflow most likely won't fix your StackOverflowExceptions, because you will get more overflown stacks as you are looking for something to Ctrl-C and Ctrl-V
  • StackUnderflowException
    • no, StackOverflow is still not going to help a lot
  • OutOfMemoryError
    • I hope it's not a memory leak
  • IOException 和其他 java.io.XxxException
  • 安全异常
  • 堆栈溢出异常
    • 不幸的是,去 StackOverflow 很可能不会修复你的 StackOverflowExceptions,因为当你正在寻找 Ctrl-C 和 Ctrl-V 的东西时,你会得到更多溢出的堆栈
  • 堆栈下溢异常
    • 不,StackOverflow 仍然不会有很大帮助
  • 内存不足错误
    • 我希望这不是内存泄漏