[英]Differences between Runtime/Checked/Unchecked/Error/Exception
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?
相反,Java 可能只是遵循一个简单的设计(只是尝试/捕获所有类型)来处理程序中的异常情况?
Since I am a new Java developer, I have also faced some difficulties for distinguishing and dealing with different types of exceptions.由于我是一个新的Java开发人员,在区分和处理不同类型的异常方面也遇到了一些困难。 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:这是
Throwable
类层次结构的图像:
[image courtesy of JavaTpoint ]. [图像由JavaTpoint 提供]。
There are three key classes to remember here: Throwable
, Exception
and Error
.这里需要记住三个关键类:
Throwable
、 Exception
和Error
。 Among these classes Exception
can be divided into two types: "Checked Exception" and "Unchecked Exception".在这些类中,
Exception
可以分为两类:“Checked Exception”和“Unchecked Exception”。
Checked Exception:检查异常:
Throwable
except RuntimeException
and Error
.Throwable
的类,除了RuntimeException
和Error
。try/catch
or indicate in the function signature that it throws
them and forcing us to deal with them in the caller.try/catch
处理它们,要么在函数签名中指出它throws
它们并迫使我们在调用者中处理它们。IOException
, SQLException
, etc.IOException
、 SQLException
等。 Unchecked Exception:未经检查的异常:
RuntimeException
are known as unchecked exceptions.RuntimeException
的类称为未经检查的异常。ArithmeticException
, NullPointerException
, ArrayIndexOutOfBoundsException
, etc.ArithmeticException
、 NullPointerException
、 ArrayIndexOutOfBoundsException
等。ArithmeticException
, which can be avoided by a simple check on the divisor.ArithmeticException
,这可以通过对除数进行简单检查来避免。 Similarly we can avoid NullPointerException
by simply checking the references: if (object != null)
or even using better techniques .NullPointerException
: if (object != null)
或者甚至使用更好的技术。 Error:错误:
Error
refers to an irrecoverable situation that is not being handled by a try/catch
. Error
是指无法由try/catch
处理的不可恢复情况。OutOfMemoryError
, VirtualMachineError
, AssertionError
, etc.OutOfMemoryError
、 VirtualMachineError
、 AssertionError
等。 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.除了Stephen C的回答我想说:异常处理是 Java 中相对昂贵的操作。 We should not put all exceptional situation in a
try/catch
block.我们不应该将所有异常情况都放在
try/catch
块中。 Excessive use of try/catch
s may hamper program performance.过度使用
try/catch
可能会影响程序性能。
In conclusion, Exception
s should be handled programmatically whenever possible.总之,应尽可能以编程方式处理
Exception
。 On the other hand, we cannot handle Error
s, so these might be some logical reasons why there are many types of exceptions.另一方面,我们无法处理
Error
,所以这些可能是存在多种异常类型的一些合乎逻辑的原因。
Throwable is at the top off all exceptions. Throwable 位于所有异常的顶部。 Underneath Throwable you have Error and Exception.
在 Throwable 下面你有错误和异常。 Underneath Exception you have RuntimeException.
在异常下面你有运行时异常。
Java has two types of exceptions - checked and unchecked. Java 有两种类型的异常 - 已检查和未检查。 Checked exceptions are enforced by the compiler (you have to declare them in the throws clause and catch them eventually).
检查异常由编译器强制执行(您必须在 throws 子句中声明它们并最终捕获它们)。 Unchecked exceptions are not enforced for catching or declaring in throws clause.
在 throws 子句中捕获或声明不强制执行未经检查的异常。
(Controversial part of the answer) (答案中有争议的部分)
Throwable exists so that there is a parent for all exception types. Throwable 存在,因此所有异常类型都有一个父级。 You should never declare that you throw Throwable and never catch it (unless you really really really know what you are doing).
你永远不应该声明你抛出 Throwable 并且永远不会抓住它(除非你真的真的很清楚自己在做什么)。
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.存在错误以指示运行时环境问题,您的程序可能无法从中恢复的问题,例如格式错误的类文件或 VM 内存不足。 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.异常作为所有非程序员错误的根存在(有关此“异常”的信息,请参阅 RuntimeException),例如由于磁盘已满而无法创建文件。 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. RuntimeException 存在以指示所有程序员错误,例如越过数组的末尾或调用空对象上的方法。 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's answer explains clearly what the exception classes mean. TofuBeer 的回答清楚地解释了异常类的含义。
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?
相反,Java 可能只是遵循一个简单的设计(只是尝试/捕获所有类型)来处理程序中的异常情况?
Why?为什么? Because they are necessary!
因为它们是必需的! Without those 4 classes, handling exceptions by broad category would be impractical.
如果没有这 4 个类,按大类处理异常将是不切实际的。
Error
class?Error
类,您将如何捕获“所有致命的 JVM 错误”?Exception
class?Exception
类,您将如何捕获“所有非 JVM 致命错误的Exception
?RuntimeException
class?RuntimeException
类,您将如何捕获“所有未经检查的异常”?Difference between Checked and unchecked exceptions: Checked 和 unchecked 异常的区别:
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 . [1] 检查异常表示编译器检查异常。 It means that compiler mandates that such exception to be handled by try-catch block or throws keyword.
这意味着编译器要求此类异常由 try-catch 块或 throws 关键字处理。
[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. [2] 未经检查的异常是编译器没有提供任何授权的异常,因为它们可以由开发人员通过编码/编程来解决,因为控制流是可控的,如 ArithmeticException、NullPointerException ArrayIndexOutOfBoundsException、IllegalArgumentException 等。
I call it “Exception-Identity-Test” where you take any random exception from java doc and just ask it one question.我称之为“异常身份测试” ,您可以从 java doc 中获取任何随机异常,然后只问一个问题。 “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.如果异常为YES,则它是未检查的异常,因为这可以通过更改代码或解决某些计算错误等来解决。
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另一方面,如果异常表示否,那么这就是检查异常,因为在检查异常控制流程中,如果有人更改了数据库密码或有人拔掉了网线,连接超时(ConnectException),某些资源未找到( FileNotFoundException, ClassNotFound), SQLException, InvocatonTargetException 等,这些是编程无法解决的
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. Checked Exceptions : Checked Exceptions是可以在编译时检测、识别和检查的异常。 If a code block throws a checked exception then the method must handle the exception or it must specify the exception using
throws
keyword.如果代码块抛出已检查的异常,则该方法必须处理该异常或必须使用
throws
关键字指定异常。
Example :示例:
public void testDB() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver Loaded"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/selenium","root","root"); System.out.println("Connected to MySQL DB"); }
We either need to specify list of exceptions using throws or we need to use try-catch{}
block.我们要么需要使用 throws 指定异常列表,要么需要使用
try-catch{}
块。 I have demonstrated the useage of throws
in the below program.我已经在下面的程序中演示了
throws
的用法。
Unchecked Exceptions : Unchecked Exceptions are not checked at compiled time. Unchecked Exceptions : Unchecked Exceptions在编译时不被检查。 Java exceptions under
Error
and RuntimeException
classes are unchecked exceptions and everything else under throwable is checked. Error
和RuntimeException
类下的 Java 异常是未经检查的异常,而throwable下的所有其他异常都经过检查。
Summary : If a client can reasonably be expected to recover from an exception, make it a checked exception.
摘要:如果可以合理地期望客户端从异常中恢复,请将其设置为已检查异常。 If a client cannot do anything to recover from the exception, make it an unchecked exception.
如果客户端无法从异常中恢复,请将其设为未经检查的异常。
The figure below shows the hierarchy of the Exception classes. 下图显示了Exception类的层次结构。 The base class for all Exception objects is
java.lang.Throwable
, together with its two subclasses java.lang.Exception
and java.lang.Error
. 所有Exception对象的基类都是
java.lang.Throwable
,以及它的两个子类java.lang.Exception
和java.lang.Error
。
The Error
class describes internal system errors (eg, VirtualMachineError
, LinkageError
) that rarely occur. Error
类描述了很少发生的内部系统错误(例如, VirtualMachineError
, LinkageError
)。 If such an error occurs, there is little that you can do and the program will be terminated by the Java runtime. 如果发生此类错误,您几乎无法执行该操作,Java运行时将终止该程序。
The Exception
class describes the error caused by your program (eg FileNotFoundException
, IOException
). Exception
类描述了程序引起的错误(例如FileNotFoundException
, IOException
)。 These errors could be caught and handled by your program (eg, perform an alternate action or do a graceful exit by closing all the files, network and database connections). 这些错误可以由您的程序捕获和处理(例如,执行备用操作或通过关闭所有文件,网络和数据库连接来执行正常退出)。
Checked vs Unchecked Checked vs Unchecked
As illustrated, the subclasses of Error
and RuntimeException
are known as unchecked exceptions. 如图所示,
Error
和RuntimeException
的子类称为未经检查的异常。 These exceptions are not checked by the compiler, and hence, need not be caught or declared to be thrown in your program. 编译器不会检查这些异常,因此不需要捕获或声明在程序中抛出这些异常。 This is because there is not much you can do with these exceptions.
这是因为您可以对这些异常做很多事情。 For example, a "divide by 0" triggers an
ArithmeticException
, array index out-of-bound triggers an ArrayIndexOutOfBoundException
, which are really programming logical errors that shall be been fixed in compiled-time, rather than leaving it to runtime exception handling. 例如,“除以0”触发
ArithmeticException
,数组索引超出绑定触发ArrayIndexOutOfBoundException
,它们实际上是编译逻辑错误,应该在编译时修复,而不是将其留给运行时异常处理。
All the other exception are called checked exceptions. 所有其他异常都称为检查异常。 They are checked by the compiler and must be caught or declared to be thrown.
它们由编译器检查,必须被捕获或声明被抛出。
RuntimeException
and its subclasses are not checked by the compiler and need not be declared in the method's signature. 编译器不检查
RuntimeException
及其子类,也不需要在方法的签名中声明。 Therefore, use them with care, as you will not be informed and may not be aware of the exceptions that may occur by using that method (and therefore do not have the proper exception handling codes) – a bad software engineering practice. 因此,请谨慎使用它们,因为您不会被告知并且可能不会意识到使用该方法可能发生的异常(因此没有正确的异常处理代码) - 一种糟糕的软件工程实践。
运行时异常为您提供了避免捕获和声明异常的灵活性。
Exceptions are two types in java:
1. **Checked Exception: The exceptions which are checked by compiler.
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.例如:我们正在对文件进行操作,那么编译器会要求您通过 try-catch 块或 throws 关键字来处理 IOException。
2. Unchecked Exception: The exceptions which are not checked by compiler at run time.
For example: If you are performing operation on an object without creating it;例如:如果您正在对一个对象进行操作而不创建它; in this case you'll get NullPointerException.
在这种情况下,您将得到 NullPointerException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.