Java exception handling
Exceptions are some errors in the program, but not all errors are exceptions, and errors can sometimes be avoided.
For example, if your code is missing a semicolon, the result will be an error java.lang.Error; if you use System.out.println(11/0), then you are because If you use 0 as the divisor, a java.lang.ArithmeticException will be thrown.
There are many reasons for exceptions, which usually include the following categories:
- ## The user entered illegal data.
- The file to be opened does not exist.
- The connection is interrupted during network communication, or the JVM memory overflows.
Checked exceptions:The most representative checked exceptions are exceptions caused by user errors or problems, which cannot be foreseen by the programmer. For example, when trying to open a file that does not exist, an exception occurs. These exceptions cannot be simply ignored at compile time.
Runtime exceptions: Runtime exceptions are exceptions that may be avoided by the programmer. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
Error: An error is not an exception, but a problem beyond the programmer's control. Errors are often ignored in code. For example, when the stack overflows, an error occurs that cannot be checked during compilation.
Exception class hierarchyAll exception classes are subclasses inherited from the java.lang.Exception class. Exception class is a subclass of Throwable class. In addition to the Exception class, Throwable also has a subclass Error. Java programs generally do not catch errors. Errors generally occur when serious failures occur, and they are outside the scope of processing by Java programs. Error is used to indicate errors that occur in the runtime environment. For example, JVM memory overflow. Normally, programs do not recover from errors. The exception class has two main subclasses: IOException class and RuntimeException class. In Java's built-in classes (explained next), there are most commonly used checked and non-checked exceptions.
Java built-in exception classesThe Java language defines some exception classes in the java.lang standard package. Subclasses of the standard runtime exception classes are the most common exception classes. Since the java.lang package is loaded into all Java programs by default, most exceptions inherited from the runtime exception class can be used directly.
Java also defines some other exceptions according to each class library. The following table lists Java's non-checked exceptions.
Exception | Description |
---|---|
This exception is thrown when an abnormal operation condition occurs. For example, when an integer is "divided by zero", an instance of this class is thrown. | |
Exception thrown when accessing an array with an illegal index. An index is an illegal index if it is negative or greater than or equal to the array size. | |
Exception thrown when trying to store an object of the wrong type into an object array. | |
This exception is thrown when an attempt is made to cast an object to a subclass that is not an instance. | |
The exception thrown indicates that an illegal or incorrect parameter was passed to the method. | |
The exception thrown indicates that a thread has attempted to wait on the object's monitor, or has attempted to notify another thread that is waiting on the object's monitor without itself specifying a monitor. | |
A signal generated when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the appropriate state for the requested operation. | |
Exception thrown when the thread is not in the appropriate state required by the requested operation. | |
Thrown when indicating that a sort index (such as a sort on an array, string, or vector) is out of range. | |
NegativeArraySizeException | This exception is thrown if the application attempts to create an array with a negative size. |
NullPointerException |
This exception is thrown when an application attempts to use null where an object is expected |
This exception is thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted into the appropriate format. | |
Exception thrown by the security manager to indicate a security violation. | |
This exception is thrown by the | String method and indicates that the index is either negative or exceeds the size of the string. |
This exception is thrown when the requested operation is not supported. |
Exception | Description |
---|---|
When the application attempts to load a class, the corresponding class cannot be found and this exception is thrown. | |
This exception is thrown when the | clone method in the Object class is called to clone an object, but the object's class cannot implement the Cloneable interface. |
This exception is thrown when access to a class is denied. | |
This is thrown when an attempt is made to create an instance of a class using the | newInstance method in the Class class, and the specified class object cannot be instantiated because it is an interface or an abstract class. abnormal. |
This exception is thrown when a thread is interrupted by another thread. | |
The requested variable does not exist | |
The requested method does not exist |
Serial number | Methods and instructions |
---|---|
1 | public String getMessage() Returns detailed information about the exception that occurred. This message is initialized in the constructor of the Throwable class. |
2 | public Throwable getCause() Returns a Throwable object representing the cause of the exception. |
3 | public String toString() Use the result of getMessage() to return the concatenated name of the class. |
4 | public void printStackTrace() Print the toString() result and stack level to System.err, the error output stream. |
5 | public StackTraceElement [] getStackTrace() Returns an array containing stack levels. The element with index 0 represents the top of the stack, and the last element represents the bottom of the method call stack. |
6 | public Throwable fillInStackTrace() Populates the Throwable object stack level with the current call stack level, adding to any previous information in the stack level. |
Catch exceptions
Use try and catch keywords to catch exceptions. Try/catch code blocks are placed where exceptions may occur.
The code in the try/catch code block is called protection code. The syntax for using try/catch is as follows:
try { // 程序代码 }catch(ExceptionName e1) { //Catch 块 }
The Catch statement contains a declaration of the exception type to be caught. When an exception occurs in the protected code block, the catch block following the try will be checked.
If the exception that occurs is contained in a catch block, the exception will be passed to the catch block, which is the same as passing a parameter to a method.
Example
The following example declares an array with two elements. When the code attempts to access the third element of the array, an exception will be thrown.
// 文件名 : 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"); } }
The output result of compiling and running the above code is as follows:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
Multiple capture blocks
A try code block followed by multiple catch code blocks is called multiple capture.
The syntax of multiple catch blocks is as follows:
try{ // 程序代码 }catch(异常类型1 异常的变量名1){ // 程序代码 }catch(异常类型2 异常的变量名2){ // 程序代码 }catch(异常类型2 异常的变量名2){ // 程序代码 }
The above code segment contains 3 catch blocks.
You can add any number of catch blocks after the try statement.
If an exception occurs in the protection code, the exception is thrown to the first catch block.
If the data type of the thrown exception matches ExceptionType1, it will be caught here.
If there is no match, it will be passed to the second catch block.
This is the case until the exception is caught or passes all catch blocks.
Example
This example shows how to use multiple try/catch.
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; }
throws/throw keyword:
If a method does not catch a checked exception, then the method must be declared using the throws keyword. The throws keyword is placed at the end of the method signature.
You can also use the throw keyword to throw an exception, whether it is newly instantiated or just caught.
The declaration of the following method throws a RemoteException:
import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
A method can be declared to throw multiple exceptions, separated by commas.
For example, the following method declaration throws RemoteException and InsufficientFundsException:
import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition }
finally keyword
The finally keyword is used to create a function that is executed after the try code block code block.
No matter whether an exception occurs or not, the code in the finally code block will always be executed.
In the finally code block, you can run cleanup statements and other finishing statements.
The finally code block appears at the end of the catch code block, and the syntax is as follows:
try{ // 程序代码 }catch(异常类型1 异常的变量名1){ // 程序代码 }catch(异常类型2 异常的变量名2){ // 程序代码 }finally{ // 程序代码 }
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"); } } }
The compilation and running results of the above example are as follows:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
Note the following Matter:
catch cannot exist independently of try.
It is not mandatory to add finally block after try/catch.
There cannot be neither a catch block nor a finally block after the try code.
No code can be added between try, catch, and finally blocks.
Declare custom exceptions
In Java you can customize exceptions. There are a few things to keep in mind when writing your own exception classes.
All exceptions must be subclasses of Throwable.
If you want to write a checked exception class, you need to inherit the Exception class.
If you want to write a runtime exception class, you need to inherit the RuntimeException class.
You can define your own exception class as follows:
class MyException extends Exception{ }
The exception class created by inheriting only the Exception class is a checked exception class.
The following InsufficientFundsException class is a user-defined exception class, which inherits from Exception.
An exception class, like any other class, contains variables and methods.
Example
// 文件名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; } }
To show how to use our custom exception class,
Include a withdraw() method in the following CheckingAccount class to throw an InsufficientFundsException exception.
// 文件名称 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; } }
The following BankDemo program demonstrates how to call the deposit() and withdraw() methods of the CheckingAccount class.
//文件名称 BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing 0..."); c.deposit(500.00); try { System.out.println("\nWithdrawing 0..."); c.withdraw(100.00); System.out.println("\nWithdrawing 0..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } } }
Compile the above three files and run the program BankDemo. The results are as follows:
Depositing 0... Withdrawing 0... Withdrawing 0... Sorry, but you are short 0.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13)
General exceptions
There are two types defined in Java exceptions and errors.
JVM(JavaVirtual Machine)Exception: Exception thrown by JVM or error. For example: NullPointerException class, ArrayIndexOutOfBoundsException class, ClassCastException class.
Program level exception: Exception thrown by a program or API program. For example, IllegalArgumentException class, IllegalStateException class.