To make a Java program as robust as possible it needs to be able to handle exceptions. The compiler does its part by not allowing you to compile a program until it is syntactically correct and can also point out checked exceptions that must be handled. But the exceptions that are likely to cause the most headaches are the ones that appear once the program is running. To help handle these exceptions the Java language provides the try-catch-finally blocks.
为了使Java程序尽可能健壮,它需要能够处理异常 。 编译器通过在语法上正确之前不允许您编译程序来发挥作用,并且还可以指出必须处理的检查异常。 但是,最容易引起头痛的异常是程序运行后出现的异常。 为了帮助处理这些异常, Java语言提供了try-catch-finally块。
尝试块 ( The try Block )
The
的
try
block encases any statements that might cause an exception to occur. For example, if you are reading data from a file using the
FileReader
class, it's expected that you handle the
IOExceptions
associated with using a
FileReader
object, for example,
FileNotFoundException
and
IOException
. To ensure this happens, you can place the statements that deal with creating and using the
FileReader
object inside a
try
block:However, the code is incomplete because, in order for the exception to be handled, we need a place for it to be caug
捕获块 ( catch block.The catch Block )
The
的
catch
block(s) provide a place to handle the exception thrown by the statements within a
try
block. The
catch
block is defined directly after the
try
block. It must specify the type of exception it is handling. For example, the
FileReader
object defined in the code above is capable of throwing a
FileNotFoundException
or an
IOException
. We can specify two
catch
blocks to handle both of
FileNotFoundExceptioncatch
block we could place code to ask the user to find the file for us and then try to read the file again. In the
IOException
catch block, we might just pass on the I/O error to the user and ask them to try something else. Either way, we have provided a way for the program to catch an exception and handle it in a controlled manner.
In Java SE 7, it became possible to handled mul
在Java SE 7中,可以处理多个
catch
block. If the code we wanted to place in the two
catch
blocks above was exactly the same we could write the code like this instead:In order to do a bit of housekeeping as far as resources go, we can add a finally block. After all, we want to release the file we have been reading fro
最后一块 ( The finally Block )
The statements in the finally block are always executed. This is useful to clean up resources in the event of the try block executing without an exception and in the cases when there is an exception. In both eventualities, we can close the file we have been using.
finally块中的语句始终执行。 这在执行try块而没有异常的情况下以及有异常的情况下对清理资源很有用。 在两种情况下,我们都可以关闭我们一直在使用的文件。
The finally block appears directly after the last catch block:
finally块直接出现在最后一个catch块之后:
翻译自: https://www.thoughtco.com/the-try-catch-finally-blocks-2033909