Summary
A program can use exceptions to indicate that an error occurred. To throw an exception, use the throw statement and provide it with an exception object — a descendant of Throwable — to provide information about the specific error that occurred. A method that throws an uncaught, checked exception must include a throws clause in its declaration.
程序可以使用异常去表示一个错误发生了。为了抛出异常,使用throw
子句并提供一个异常对象 - Throwable
的子孙 - 提供关于发生的具体异常的信息。抛出一个未捕获、受检查异常的方法必须在它的声明中包含throws
子句。
A program can catch exceptions by using a combination of the try, catch, and finally blocks.
- The try block identifies a block of code in which an exception can occur.
- The catch block identifies a block of code, known as an exception handler, that can handle a particular type of exception.
- The finally block identifies a block of code that is guaranteed to execute, and is the right place to close files, recover resources, and otherwise clean up after the code enclosed in the try block.
程序通过使用try
、catch
、finally
语句块,能捕获异常。
try
语句块表示一个代码块中可能发生异常。catch
语句块表示一个代码块,被称为异常处理器,它能处理一种特殊异常类型。finally
语句块表示将被保证执行的一个代码块,是关闭文件、恢复资源、以及其它在try
语句块中的代码之后执行清理的合适位置。
The try statement should contain at least one catch block or a finally block and may have multiple catch blocks.
try`语句必须包含至少一个
catch语句块,或是一个
finally语句块以及可能有多个
catch`语句块。
The class of the exception object indicates the type of exception thrown. The exception object can contain further information about the error, including an error message. With exception chaining, an exception can point to the exception that caused it, which can in turn point to the exception that caused it, and so on.
异常对象的类表示被抛出异常的类型。异常对象能够包含更多关于错误的信息,包括错误消息。在异常链中,一个异常可以指向导致它的异常,被指向的异常也可以指向导致它的异常,依次类推。