Java 简明教程
Java - Exceptions
What Is an Exception in Java?
异常(或特殊事件)是在程序执行期间产生的问题。当 Exception 发生时,程序的正常流程会中断,程序/应用程序异常终止,这是不建议的,因此,这些异常需要被处理。
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
Why Exception Occurs?
异常可能由于许多不同的原因而发生。以下是一些发生异常的情况。
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
-
A user has entered an invalid data.
-
A file that needs to be opened cannot be found.
-
A network connection has been lost in the middle of communications or the JVM has run out of memory.
其中一些异常是由用户错误引起的,另一些是由程序员错误引起的,还有一些是由某种方式失效的物理资源引起的。
Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
Java Exception Categories
基于这些,我们有以下类别的异常。您需要理解它们才能了解 Java 中的异常处理是如何工作的。
Based on these, we have the following categories of Exceptions. You need to understand them to know how exception handling works in Java.
-
Checked exceptions
-
Unchecked exceptions
-
Errors
Java Checked Exceptions
检查异常是由编译器在编译时检查(通知)的异常,这些异常也称为编译时异常。这些异常不能简单地被忽略,程序员应该处理(处理)这些异常。
A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions.
例如,如果您在程序中使用 FileReader 类从文件中读取数据,如果其构造函数中指定的文件不存在,则会发生 FileNotFoundException,并且编译器会提示程序员处理该异常。
For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn’t exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
如果您尝试编译上述程序,您将获得以下异常。
If you try to compile the above program, you will get the following exceptions.
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Note − 由于 FileReader 类的 read() 和 close() 方法会抛出 IOException,您可以观察到编译器通知处理 IOException,以及 FileNotFoundException。
Note − Since the methods read() and close() of FileReader class throws IOException, you can observe that the compiler notifies to handle IOException, along with FileNotFoundException.
Java Unchecked Exceptions
未检查异常是发生在执行时的异常。这些异常也称为运行时异常。其中包括编程错误,例如逻辑错误或不当使用 API。运行时异常在编译时会被忽略。
An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
例如,如果您在程序中声明了一个长度为 5 的数组,并尝试调用该数组的第 6 个元素,则会发生 ArrayIndexOutOfBoundsException 异常。
For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
如果您编译并执行上述程序,您将获得以下异常。
If you compile and execute the above program, you will get the following exception.
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Java Errors
这些根本不是异常,而是发生在用户或程序员控制范围之外的问题。错误通常在您的代码中被忽略,因为您很少能对错误做任何事情。例如,如果发生堆栈溢出,则会产生一个错误。它们也在编译时被忽略。
These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Java Exception Hierarchy
所有异常类都是 java.lang.Exception 类的子类型。异常类是类的子类。除异常类之外,还有一个子类称为 Error,它源自 Throwable 类。
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.
错误是发生在严重故障的情况下的异常条件,这些错误不受 Java 程序处理。生成错误是为了指示由运行时环境生成的错误。示例:JVM 已用完内存。通常,程序无法从错误中恢复。
Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.
Exception 类有两个主要子类:IOException 类和 RuntimeException 类。
The Exception class has two main subclasses: IOException class and RuntimeException Class.
以下列出了最常见的 Java’s Built-in Exceptions检查项和未检查项。
Following is a list of most common checked and unchecked Java’s Built-in Exceptions.
Java Exception Class Methods
以下是 Throwable 类中提供的重要方法的列表。
Following is the list of important methods available in the Throwable class.
Sr.No. |
Method & Description |
1 |
public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. |
2 |
public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. |
3 |
public String toString() Returns the name of the class concatenated with the result of getMessage(). |
4 |
public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. |
5 |
public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. |
6 |
public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. |
Catching Exceptions: Exception Handling in Java
使用 try 和 catch 关键字组合的方法捕获异常。一个 try/catch 块被放置在可能生成异常的代码周围。try/catch 块内的代码被称为受保护代码,try/catch 使用的语法如下所示 −
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
容易产生异常的代码被放置在 try 块中。当异常发生时,该发生的异常由与它关联的 catch 块处理。每个 try 块应该紧接着一个 catch 块或 finally 块。
The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.
catch 语句涉及声明你试图捕获的异常类型。如果受保护代码中发生异常,则检查 try 之后的 catch 块(或块)。如果发生的异常类型被列在一个 catch 块中,则异常被传递到 catch 块中,就像一个参数被传递到一个方法参数中一样。
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Example: Demonstrating Exception Handling
在下面的示例中,一个数组被声明为带有 2 个元素。然后代码尝试访问数组的第 3 个元素,从而抛出一个异常。
In following example, an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple Catch Blocks
一个 try 块可以跟随多个 catch 块。多个 catch 块的语法如下所示 −
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
前面的语句演示了三个 catch 块,但是你可以在一个 try 之后可以有任意数量的 catch 块。如果受保护代码中发生异常,则异常被抛到列表中的第一个 catch 块。如果抛出的异常的数据类型匹配 ExceptionType1,则异常在该处被捕获。如果没有,则异常传递到第二个 catch 语句。这将持续到异常被捕获或者通过所有 catch,在这种情况下,当前方法停止执行并且异常被抛到调用堆栈上先前的那个方法。
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Example
这里有一个代码段显示如何使用多个 try/catch 语句。
Here is code segment showing how to use multiple try/catch statements.
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}
Catching Multiple Type of Exceptions
自 Java 7 起,你可以使用一个 catch 块处理多个异常,这个功能简化了代码。以下是处理它的方法 −
Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it −
catch (IOException|FileNotFoundException ex) {
logger.log(ex);
throw ex;
The Throws/Throw Keywords
如果一个方法没有处理已检查异常,则方法必须使用 throws 关键字声明它。throws 关键字显示在方法签名的末尾。
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.
你可以使用 throw 关键字抛出一个异常,它既可以是一个新实例化的异常,也可以是你刚捕获的异常。
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.
尝试理解 throws 和 throw 关键字之间的差异,throws 用于推迟对已检查异常的处理,而 throw 用于显式地调用一个异常。
Try to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.
以下方法声明它抛出一个 RemoteException −
The following method declares that it throws a RemoteException −
Example
import java.io.*;
public class className {
public void deposit(double amount) throws RemoteException {
// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}
一个方法可以声明它抛出多个异常,在这种情况下,异常被声明在一个以逗号分隔的列表中。例如,以下方法声明它抛出 RemoteException 和 InsufficientFundsException −
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException −
The Finally Block
finally 块跟随一个 try 块或一个 catch 块。无论异常是否发生,finally 代码块始终执行。
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
使用 finally 块允许你运行你想要执行的任何清理类型语句,无论受保护代码中发生什么。
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
finally 块出现在 catch 块的末尾并且具有以下语法 −
A finally block appears at the end of the catch blocks and has the following syntax −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
注意以下内容 −
Note the following −
-
A catch clause cannot exist without a try statement.
-
It is not compulsory to have finally clauses whenever a try/catch block is present.
-
The try block cannot be present without either catch clause or finally clause.
-
Any code cannot be present in between the try, catch, finally blocks.
The try-with-resources
通常,当我们使用任何资源(例如流、连接等)时,我们必须使用 finally 块显式关闭它们。在以下程序中,我们正在使用 FileReader 从文件中读取数据,并且我们正在使用 finally 块关闭它。
Generally, when we use any resources like streams, connections, etc. we have to close them explicitly using finally block. In the following program, we are reading data from a file using FileReader and we are closing it using finally block.
Example
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadData_Demo {
public static void main(String args[]) {
FileReader fr = null;
try {
File file = new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
try-with-resources(也称为 automatic resource management)是 Java 7 引入的一种新的异常处理机制,它会自动关闭 try catch 块内使用的资源。
try-with-resources, also referred as automatic resource management, is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try catch block.
要使用此语句,您只需在括号中声明所需资源,创建的资源将在块结束时自动关闭。以下是 try-with-resources 语句的语法。
To use this statement, you simply need to declare the required resources within the parenthesis, and the created resource will be closed automatically at the end of the block. Following is the syntax of try-with-resources statement.
Syntax
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}
}
以下是使用 try-with-resources 语句读取文件中的数据的程序。
Following is the program that reads the data in a file using try-with-resources statement.
Example
import java.io.FileReader;
import java.io.IOException;
public class Try_withDemo {
public static void main(String args[]) {
try(FileReader fr = new FileReader("E://file.txt")) {
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}
}
}
在使用 try-with-resources 语句时,需要注意以下几点。
Following points are to be kept in mind while working with try-with-resources statement.
-
To use a class with try-with-resources statement it should implement AutoCloseable interface and the close() method of it gets invoked automatically at runtime.
-
You can declare more than one class in try-with-resources statement.
-
While you declare multiple classes in the try block of try-with-resources statement these classes are closed in reverse order.
-
Except the declaration of resources within the parenthesis everything is the same as normal try/catch block of a try block.
-
The resource declared in try gets instantiated just before the start of the try-block.
-
The resource declared at the try block is implicitly declared as final.
User-defined Exceptions in Java
您可以在 Java 中创建自己的异常。在编写自己的异常类时,牢记以下几点:
You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes −
-
All exceptions must be a child of Throwable.
-
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
-
If you want to write a runtime exception, you need to extend the RuntimeException class.
Syntax
我们可以按如下方式定义自己的 Exception 类:
We can define our own Exception class as below −
class MyException extends Exception {
}
您只需要扩展预定义的 Exception 类即可创建您自己的 Exception。这些被认为是已检查的异常。以下 InsufficientFundsException 类是一个用户定义的异常,它扩展了 Exception 类,使其成为一个已检查的异常。异常类就像任何其他类,包含有用的字段和方法。
You just need to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.
Example: Creating user-defined exception
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
为了演示如何使用我们用户定义的异常,以下 CheckingAccount 类包含一个 withdraw() 方法,该方法会抛出一个 InsufficientFundsException。
To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}
以下 BankDemo 程序演示如何调用 CheckingAccount 的 deposit() 和 withdraw() 方法。
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
编译以上三个文件并运行 BankDemo。这将产生以下结果:
Compile all the above three files and run BankDemo. This will produce the following result −
Output
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Common Java Exceptions
在 Java 中,可以定义两类异常和错误。
In Java, it is possible to define two catergories of Exceptions and Errors.
-
JVM Exceptions − These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.
-
Programmatic Exceptions − These exceptions are thrown explicitly by the application or the API programmers. Examples: IllegalArgumentException, IllegalStateException.