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), with 0 as the divisor, will throw Java Exception for lang.arithmeticexception.
there are many reasons for exceptions, usually including the following categories: the user has entered illegal data; The file to open does not exist; Connection interruption during network communication; JVM memory overflow. Some of these exceptions are caused by user errors, some are caused by program errors, and others are caused by physical errors.
to understand how Java exception handling works, you need to master the following three types of exceptions:
- Checking exception: the most representative checking exception is the exception caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a nonexistent file, an exception occurs. These exceptions cannot be simply ignored at compile time.
- Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.
- Error: an error is not an exception, but a problem out of the programmer's control. For example, when the stack overflows, an error occurs that cannot be checked at compile time.
Hierarchy of Exception class
all exception classes are from Java Lang. exception class is a subclass inherited from. Exception class is a subclass of Throwable class. In addition to the exception class, Throwable also has a subclass Error, which is used to indicate errors in the runtime environment, such as JVM memory overflow. Generally, the program will not recover from the Error. The exception class has two main subclasses: IOException class and RuntimeException class.
Java built-in exception class
Java defines some exception classes in Java Lang standard package. Subclasses of the standard runtime exception class are the most common exception classes. Because Java Lang package is loaded into all Java programs by default, so most exceptions inherited from runtime exception classes can be used directly.
Java also defines some other exceptions according to various class libraries. The non checking exceptions of Java are listed below:
- ArithmeticException: this exception is thrown when an abnormal operation condition occurs. For example, when an integer is divided by zero, Java will throw such an exception.
- ArrayIndexOutOfBoundsException: an exception thrown when accessing an array with an illegal index. If the index is negative or greater than or equal to the array size, the index is illegal.
- ArrayStoreException: an exception thrown when trying to store an object of the wrong type into an object array.
- ClassCastException: thrown when trying to cast an object to a subclass that is not an instance.
- IllegalArgumentException: an exception thrown indicates that an illegal or incorrect parameter was passed to the method.
- IllegalMonitorStateException: an exception thrown indicates that a thread has tried to wait for the monitor of the object, or tried to notify other monitors waiting for the object without specifying the monitor itself.
- IllegalStateException: 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 required by the requested operation.
- IllegalThreadStateException: an exception thrown when a thread is not in the appropriate state required by the requested operation.
- IndexOutOfBoundsException: thrown when a sort index (such as sorting 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: thrown when an application attempts to use null where an object is needed.
- NumberFormatException: this exception is thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format.
- SecurityException: an exception thrown by the security manager indicating a security violation.
- StringIndexOutOfBoundsException: this exception is thrown by the String method, indicating that the index is either negative or exceeds the size of the String.
- Unsupported operationexception: this exception is thrown when an unsupported operation occurs.
The following table lists the Java definitions in Java Checking exception classes in Lang package:
- ClassNotFoundException: when the application loads a class, if the corresponding class cannot be found, this exception will be thrown.
- CloneNotSupportedException: 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 clonable interface.
- IllegalAccessException: this exception is thrown when access to a class is denied.
- InstantiationException: this exception 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.
- InterruptedException: this exception is thrown when a thread is interrupted by another thread.
- NoSuchFieldException: the requested variable does not exist.
- NoSuchMethodException: the requested method does not exist.
Exception method
the following list is the main method of Throwable class:
- public String getMessage(): returns detailed information about the exception that occurred. This message is initialized in the constructor of the Throwable class.
- public Throwable getCause(): returns a Throwable object representing the cause of the exception.
- public String toString(): use the result of getMessage to return the string name of the class.
- public void printStackTrace(): print the toString result and stack hierarchy to system Err, the error output stream.
- public StackTraceElement [] getStackTrace(): returns an array containing stack hierarchy. The element with subscript 0 represents the top of the stack, and the last element represents the bottom of the method call stack.
- public Throwable fillInStackTrace(): fills the stack hierarchy of Throwable objects with the current call stack hierarchy and adds it to any previous information in the stack hierarchy.
Catch exception
exceptions can be caught by using the try and catch keywords, and the try/catch code block is placed where exceptions may occur. The code in the try/catch code block is called protection code. The syntax of using try/catch is as follows:
try { /* Program code */ } catch(ExceptionName e1) { /* Catch block */ }
The catch statement contains a declaration of the type of exception to catch. When an exception occurs in the protection code block, the catch block after the try is checked. If the exception is contained in the catch block, the exception will be passed to the catch block, which is the same as passing a parameter to the method.
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:
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"); } }
Execution results:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
Multiple capture block
the case where a try code block is followed by multiple catch code blocks is called multiple capture. Any number of catch blocks can be added after the try statement:
try { /* ... */ } catch (Variable name of exception type 1) { /* ... */ } catch (Variable name of exception type 2) { /* ... */ } catch (Variable name of exception type 2) { /* ... */ }
The above code segment contains three catch blocks. If an exception occurs in the protection code, the exception is thrown to the first catch block. If the data type of the exception thrown matches ExceptionType1, it will be caught here; If it does not match, it is passed to the second catch block. In this way, until the exception is caught or passed through all catch blocks:
try { file = new FileInputStream(fileName); x = (byte) file.read(); } catch (IOException i) { i.printStackTrace(); return -1; } catch (FileNotFoundException f) { f.printStackTrace(); return -1; }
throws/throw keyword
throw is generally used when a certain logic appears in the program, and the programmer actively throws a certain type of exception:
public class ExcepTest { public static void main(String[] args) { String s = "abc"; if (s.equals("abc")) { throw new NumberFormatException(); } else { System.out.println(s); } } }
Execution results:
Exception in thread "main" java.lang.NumberFormatException at ExcepTest.main(ExcepTest.java:5)
throws is a declaration that a method may throw an exception (used when declaring a method to indicate that the method may throw an exception):
[(Modifier )] (return type) (Method name) ([parameter list]) [throws Exception class 1 [, Exception class 2]] { /* ... */ }
When a method may throw an exception, it is used to declare the exception that may be thrown, and then hand it to the upper layer method program calling it for processing:
public class ExcepTest { public static void function() throws NumberFormatException { String s = "abc"; System.out.println(Double.parseDouble(s)); } public static void main(String[] args) { try { function(); } catch (NumberFormatException e) { /* Output "non data type cannot be converted" */ System.err.println("Non data type cannot be converted"); } } }
finally keyword
finally keyword is used to create a code block executed after a try code block. Regardless of whether an exception occurs, the code in the finally code block is always executed. Finally, the code block appears at the end of the catch code block:
try { /* ... */ } catch (Variable name of exception type 1) { /* ... */ } catch (Variable name of exception type 2) { /* ... */ } finally { /* ... */ }
The code is as follows:
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"); } } }
Execution results:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
note the following:
- catch cannot exist independently of try.
- It is not mandatory to add a finally block after try/catch.
- try code cannot be followed by neither catch nor finally blocks.
- No code can be added between try, catch and finally blocks.
Declare custom exception
in Java, you can customize exceptions. When writing your own exception class, you need to remember the following points:
- All exceptions must be subclasses of Throwable.
- If you want to write a checking 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 checking Exception class. An Exception class, like any other class, contains variables and methods.
the following InsufficientFundsException class is a user-defined Exception class, which inherits from Exception. The following example is a simulation of a bank account. The identification is completed through the bank card number, and the operations of saving and withdrawing money can be carried out:
public class InsufficientFundsException extends Exception { /* amount It is used to store the money that is lacking in case of abnormality (withdrawal of more money than balance) */ private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } }
To show how to use the custom exception class, include a withraw method in the following CheckingAccount class, which may throw an InsufficientFundsException exception:
public class CheckingAccount { /* Such simulated bank accounts */ private double balance; /* balance */ private int number; /* Card number */ public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { /* save money */ balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { /* Withdraw money */ if (amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { /* Return balance */ return balance; } public int getNumber() { /* Return card number */ return number; } }
The following BankDemo program demonstrates how to call the deposit and withraw methods of the CheckingAccount class:
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(); } } }
Execution results:
Depositing $500... Withdrawing $100... Withdrawing $600... InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:18) at BankDemo.main(BankDemo.java:10) Sorry, but you are short $200.0
General exception
two types of exceptions and errors are defined in Java:
- JVM(Java virtual machine) exception: an exception or error thrown by the JVM, such as NullPointerException class, ArrayIndexOutOfBoundsException class, ClassCastException class.
- Program level exceptions: exceptions thrown by programs or API programs, such as IllegalArgumentException class and IllegalStateException class.