运行时/已检查/未检查/错误/异常之间的差异
什么是运行时异常,什么是检查/未检查异常以及错误/异常之间的区别。为什么有这么多类型?相反,Java 可能只是简单地遵循一个简单的设计(只是尝试/捕获所有类型)来处理程序中的异常情况?
What are the Runtime exceptions and what are Checked/Unchecked Exceptions and difference between Error/Exception.Why these many types? Instead Java may simply follow a simple design(just try/catch all types) to handle an abnormal condition in a program?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
由于我是一个新的Java开发人员,我在区分和处理不同类型的异常时也遇到了一些困难。这就是为什么我对这个主题做了一个简短的记录,每当我感到困惑时,我都会浏览它。这是
Throwable
类层次结构的图像:[图片由 JavaTpoint]。
这里需要记住三个关键类:
Throwable
、Exception
和Error
。其中Exception
可以分为两种类型:“Checked Exception”和“Unchecked Exception”。检查异常:
Throwable
的类,除了RuntimeException
和Error
之外。IOException
、SQLException
等Unchecked Exception:
RuntimeException
的类> 被称为未经检查的异常。ArithmeticException
、NullPointerException
、ArrayIndexOutOfBoundsException
等。if (object != null)
甚至使用 更好的技术。错误:
错误
指的是try/catch
未处理的不可恢复的情况。OutOfMemoryError
、VirtualMachineError
、AssertionError
等。为什么有这么多类型?
除了 Stephen C 的回答我想说:
异常处理是Java中相对昂贵的操作。 我们不应该将所有异常情况都放在
try/catch
块中。过度使用try/catch
可能会影响程序性能。总之,应尽可能以编程方式处理
异常
。另一方面,我们无法处理错误,因此这些可能是存在多种类型异常的一些逻辑原因。Since I am a new Java developer, I have also faced some difficulties for distinguishing and dealing with different types of exceptions. That is why I have made a short note on this topic, and whenever I get confused I go through it. Here it is with the image of the
Throwable
class hierarchy:[image courtesy of JavaTpoint].
There are three key classes to remember here:
Throwable
,Exception
andError
. Among these classesException
can be divided into two types: "Checked Exception" and "Unchecked Exception".Checked Exception:
Throwable
exceptRuntimeException
andError
.try/catch
or indicate in the function signature that itthrows
them and forcing us to deal with them in the caller.IOException
,SQLException
, etc.Unchecked Exception:
RuntimeException
are known as unchecked exceptions.ArithmeticException
,NullPointerException
,ArrayIndexOutOfBoundsException
, etc.ArithmeticException
, which can be avoided by a simple check on the divisor. Similarly we can avoidNullPointerException
by simply checking the references:if (object != null)
or even using better techniques.Error:
Error
refers to an irrecoverable situation that is not being handled by atry/catch
.OutOfMemoryError
,VirtualMachineError
,AssertionError
, etc.Why are these many types?
In addition to Stephen C's answer I want to say:
exception handling is a relatively expensive operation in Java. We should not put all exceptional situation in a
try/catch
block. Excessive use oftry/catch
s may hamper program performance.In conclusion,
Exception
s should be handled programmatically whenever possible. On the other hand, we cannot handleError
s, so these might be some logical reasons why there are many types of exceptions.Throwable 位于所有异常的顶部。
在 Throwable 下有 Error 和 Exception。
在 Exception 下面有 RuntimeException。
Java 有两种类型的异常 - 检查异常和非检查异常。检查异常由编译器强制执行(您必须在 throws 子句中声明它们并最终捕获它们)。在 throws 子句中捕获或声明时不强制执行未经检查的异常。
(答案有争议的部分)
Throwable 的存在使得所有异常类型都有一个父类。你永远不应该声明你抛出 Throwable 并且永远不会接住它(除非你真的真的知道你在做什么)。
存在错误表示运行时环境存在问题,程序可能无法从中恢复,例如格式错误的类文件或 VM 内存不足。除非您真的知道自己在做什么,否则您不应该捕获错误。
异常是所有非程序员错误的根源(请参阅 RuntimeException 了解“异常”),例如由于磁盘已满而无法创建文件。你不应该抛出、抛出或捕获异常。如果您必须捕获异常,请确保您知道自己在做什么。
RuntimeException 的存在是为了指示所有程序员错误,例如超出数组末尾或调用空对象上的方法。这些是你应该修复的事情,这样它们就不会抛出异常——这表明你,程序员,搞砸了代码。再次强调,除非你知道自己在做什么,否则你不应该发现这些。
Throwable is at the top off all exceptions.
Underneath Throwable you have Error and Exception.
Underneath Exception you have RuntimeException.
Java has two types of exceptions - checked and unchecked. Checked exceptions are enforced by the compiler (you have to declare them in the throws clause and catch them eventually). Unchecked exceptions are not enforced for catching or declaring in throws clause.
(Controversial part of the answer)
Throwable exists so that there is a parent for all exception types. You should never declare that you throw Throwable and never catch it (unless you really really really know what you are doing).
Error exists to indicate issues with the runtime environment, things that your program probably cannot recover from, such as a badly formatted class file or the VM running out of memory. You should not catch an Error unless you really know what you are doing.
Exception exists as the root for all non-programmer errors (see RuntimeException for the "exception" to this) , such as a file cannot be created because the disk is full. You should not throw, throws, or catch Exception. If you have to catch Exception make sure you know what you are doing.
RuntimeException exists to indicate all programmer error, such as going past the end of an array or calling a method on a null object. These are things that you should fix so that they do not throw exceptions - the indicate that you, the programmer, screwed up the code. Again, you should not catch these unless you know what you are doing.
TofuBeer的答案清楚地解释了异常类的含义。
为什么?因为它们是必要的!如果没有这 4 个类,按广泛类别处理异常将是不切实际的。
Error
类,您将如何捕获“所有致命 JVM 错误”?TofuBeer's answer explains clearly what the exception classes mean.
Why? Because they are necessary! Without those 4 classes, handling exceptions by broad category would be impractical.
Error
class?Exception
class?RuntimeException
class?检查和非检查异常之间的区别:
检查和非检查异常之间有很多差异,但所有差异都源于一个基本考虑,即异常是否可以由编译器解决。
要记住的要点是:
[1 ] 检查异常意味着编译器检查异常。这意味着编译器强制要求通过 try-catch 块或 throws 关键字来处理此类异常。
[2] 未经检查的异常是编译器不提供任何命令的异常,因为它们可以由开发人员通过编码/编程来解决,因为控制流是可控的,例如 ArithmeticException、NullPointerException ArrayIndexOutOfBoundsException、IllegalArgumentException 、 ETC。
我将其称为“Exception-Identity-Test”,您可以从 java 文档中随机获取任何异常,然后只问它一个问题。 “嘿例外!你能通过编程方式解决吗?”
如果异常显示是,那么它是一个未经检查的异常,因为这可以通过代码更改或解决一些计算错误等来解决。
另一方面,如果异常说否那么这是检查异常,因为检查异常控制流超出了我们的代码,就像有人更改数据库密码或有人拔掉网络电缆,连接超时(ConnectException),某些资源不是find(FileNotFoundException、ClassNotFound)、SQLException、InvocatonTargetException等,这些是无法通过编程解决的
Difference between Checked and unchecked exceptions:
We have many differences between checked and unchecked exception but all the differences originate from once basic consideration that whether the exception is solvable by compiler or not.
Points to remember are:
[1] Checked exception means Compiler checked Exceptions. It means that compiler mandates that such exception to be handled by try-catch block or throws keyword.
[2] Unchecked exceptions are the ones for which compiler doesn’t provides any mandate as they can be resolved by developer by coding/programing as the control flow is controllable like in ArithmeticException, NullPointerException ArrayIndexOutOfBoundsException, IllegalArgumentException ,etc.
I call it “Exception-Identity-Test” where you take any random exception from java doc and just ask it one question. “Hey Exception! Can you be solved programmatically?”
If the exception says YES then it is an Unchecked Exception as this can be solved by either code change or resolving some calculation mistake etc.
On the other hand if the Exception says No then this is Checked Exception as in checked Exception control flow goes out of our code like if someone changes Database passwords or someone unplugs the network cable ,connection timeout (ConnectException), some resource is not found (FileNotFoundException, ClassNotFound), SQLException, InvocatonTargetException etc. These ones cannot be resolved by programming
这篇文章总结了已检查和未检查异常以清晰简洁的方式。
受检查异常:受检查异常是可以在编译时检测、识别和检查的异常。如果代码块抛出已检查的异常,则该方法必须处理该异常,或者必须使用
throws
关键字指定该异常。示例:
我们要么需要使用 throws 指定异常列表,要么需要使用
try-catch{}
块。我在下面的程序中演示了throws
的用法。未检查异常:未检查异常在编译时不进行检查。
Error
和RuntimeException
类下的 Java 异常是未经检查的异常,并且 throwable 下的所有其他异常均经过检查。This article sumarizes Checked and Unchecked exceptions in a clear and concise way.
Checked Exceptions: Checked Exceptions are the exceptions which can be detected, identified and checked at compile time. If a code block throws a checked exception then the method must handle the exception or it must specify the exception using
throws
keyword.Example:
We either need to specify list of exceptions using throws or we need to use
try-catch{}
block. I have demonstrated the useage ofthrows
in the below program.Unchecked Exceptions: Unchecked Exceptions are not checked at compiled time. Java exceptions under
Error
andRuntimeException
classes are unchecked exceptions and everything else under throwable is checked.运行时异常为您提供了避免捕获、声明异常的灵活性。
Runtime Exceptions provide you with the flexibility to avoid catching, declaring the exceptions.
例如:我们正在对文件执行操作,那么编译器会要求您通过 try-catch 块或 throws 关键字来处理 IOException。
例如:如果您在没有创建对象的情况下对对象进行操作;在这种情况下,您将得到 NullPointerException。
For example: we you are performing operation with file, then compiler will ask you to handle IOException either by try-catch block or throws keyword.
For example: If you are performing operation on an object without creating it; in this case you'll get NullPointerException.