java.lang.RuntimeException 和 java.lang.Exception 之间的区别 [英] Difference between java.lang.RuntimeException and java.lang.Exception
问题描述
谁能解释一下java.lang.RuntimeException
和java.lang.Exception
的区别?如果我创建自己的异常,如何决定扩展哪一个?
Someone please explain the difference between java.lang.RuntimeException
and java.lang.Exception
? How do I decide which one to extend if I create my own exception?
推荐答案
通常RuntimeExceptions是异常,可以通过编程来防止.例如 NullPointerException
、ArrayIndexOutOfBoundException
.如果您在调用任何方法之前检查 null
,则永远不会发生 NullPointerException
.同样,如果您先检查索引,则永远不会发生 ArrayIndexOutOfBoundException
.RuntimeException
没有被编译器检查,所以它是干净的代码.
Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException
, ArrayIndexOutOfBoundException
. If you check for null
before calling any method, NullPointerException
would never occur. Similarly ArrayIndexOutOfBoundException
would never occur if you check the index first. RuntimeException
are not checked by the compiler, so it is clean code.
EDIT :现在人们喜欢 RuntimeException
因为它生成的代码很干净.这完全是个人选择.
EDIT : These days people favor RuntimeException
because the clean code it produces. It is totally a personal choice.
这篇关于java.lang.RuntimeException 和 java.lang.Exception 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!