Java Exception Handling and java Exception Handling
Exceptions are some errors in the program, but not all errors are exceptions, and sometimes they can be avoided.
For example, if your code is missing a semicolon, the running result indicates that the error occurs in java. lang. error; if you use System. out. println (11/0), so you do the divisor with 0, will throw java. lang. arithmeticException.
There are many causes of exceptions, usually including the following categories:
- The user entered invalid data.
- The file to be opened does not exist.
- The connection is interrupted during network communication, or the JVM memory overflows.
These exceptions are caused by user errors, program errors, and physical errors. -
To understand how Java Exception Handling works, you need to master the following three types of exceptions:
- Check exceptions:The most representative inspection exception is caused by user errors or problems, which cannot be foreseen by programmers. For example, if you want to open a non-existent file, an exception will occur, and these exceptions cannot be simply ignored during compilation.
- Runtime exception:Running exceptions may be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored during compilation.
- Error:The error is not an exception, but an issue that is out of programmer control. Errors are usually ignored in the code. For example, when the stack overflows, an error occurs and they cannot be checked during compilation.
Exception class hierarchy
All Exception classes are subclasses inherited from the java. lang. Exception class.
The Exception class is a subclass of the Throwable class. Besides the Exception class, Throwable also has a subclass Error.
Java programs usually do not capture errors. Errors generally occur in the case of serious faults outside the scope of Java program processing.
Error indicates an Error in the runtime environment.
For example, JVM memory overflow. Generally, the program will not be restored from the error.
The exception class has two main subclasses: The IOException class and the RuntimeException class.
In Java built-in classes (as described later), most common and non-checkable exceptions occur.
Java built-in exception classes
The Java language defines some exception classes in the java. lang standard package.
The subclass of the standard runtime exception class is the most common exception class. Because the java. lang Package is loaded to all Java programs by default, most exceptions inherited from runtime exception classes can be directly used.
Java also defines some other exceptions based on each class library. The following table lists non-checkable exceptions in Java.
Exception |
Description |
ArithmeticException |
This exception is thrown when an operation condition is abnormal. For example, if an integer is "divided by zero", an instance of this type is thrown. |
ArrayIndexOutOfBoundsException |
An exception thrown when an invalid index is used to access an array. If the index is negative or greater than or equal to the array size, the index is invalid. |
ArrayStoreException |
This exception is thrown when an error type object is stored in an object array. |
ClassCastException |
This exception is thrown when you try to forcibly convert an object to a subclass other than an instance. |
IllegalArgumentException |
The thrown exception indicates that an invalid or incorrect parameter is passed to the method. |
IllegalMonitorStateException |
The thrown exception indicates that a thread has tried to wait for the monitor of the object, or tried to notify another monitor that is waiting for the object without specifying the monitor itself. |
IllegalStateException |
The signal generated when the method is called at an invalid or inappropriate time. In other words, the Java environment or Java application is not in the appropriate state as required by request operations. |
IllegalThreadStateException |
The exception thrown when the thread is not in the appropriate State required by the request operation. |
IndexOutOfBoundsException |
Indicates that a Sorting index (such as sorting an array, string, or vector) is out of the range. |
NegativeArraySizeException |
This exception is thrown if the application tries to create an array with a negative size. |
NullPointerException |
When the application tries to usenull This exception is thrown. |
NumberFormatException |
This exception is thrown when the application attempts to convert a string to a numeric type but cannot convert it to an appropriate format. |
SecurityException |
An exception thrown by the security manager indicates a security violation. |
StringIndexOutOfBoundsException |
This exception is causedString Method throw, indicating that the index is negative or exceeds the size of the string. |
UnsupportedOperationException |
This exception is thrown when the request operation is not supported. |
The following table lists the checked exception classes defined by Java in the java. lang package.
Exception |
Description |
ClassNotFoundException |
When an application tries to load a class, it cannot find the corresponding class and throws this exception. |
CloneNotSupportedException |
WhenObject Classclone Method To clone an object, but the class of this object cannot be implementedCloneable This exception is thrown. |
IllegalAccessException |
This exception is thrown when a class is denied. |
InstantiationException |
When trying to useClass ClassnewInstance This exception is thrown when the specified class object cannot be instantiated because it is an interface or an abstract class. |
InterruptedException |
If a thread is interrupted by another thread, this exception is thrown. |
NoSuchFieldException |
The requested variable does not exist. |
NoSuchMethodException |
The requested method does not exist. |
Exception Method
The following lists the main methods of the Throwable class:
Serial number |
Method and description |
1 |
Public String getMessage () Returns detailed information about an exception. The message is initialized in the constructor of the Throwable class. |
2 |
Public Throwable getCause () A Throwable object is returned to indicate the cause of the exception. |
3 |
Public String toString () The cascade name of the class returned by getMessage. |
4 |
Public void printStackTrace () Print the toString () result and stack hierarchy to System. err, that is, the error output stream. |
5 |
Public StackTraceElement [] getStackTrace () Returns an array containing the stack hierarchy. 0 indicates the top of the stack, and the last element indicates the bottom of the stack of the method call stack. |
6 |
Public Throwable fillInStackTrace () Fill the Throwable object stack hierarchy with the current call stack hierarchy and add it to any previous information on the stack hierarchy. |
Capture exceptions
You can use the 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 the protection code. The try/catch syntax is as follows:
Try {// program code} catch (ExceptionName e1) {// Catch Block}
The Catch statement contains the Declaration to capture the exception type. When an exception occurs in the protection code block, the catch block after try will be checked.
If an exception is contained in a catch Block, the exception is passed to the catch block, which is the same as passing a parameter to the method.
Instance
The following example declares an array with two elements. An exception is thrown when the Code tries to access the third element of the array.
// File name: upload test. javaimport java. io. *; public class synchronized test {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 the above code compilation and running is as follows:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block
Multiple capture Blocks
A try code block is followed by multiple catch code blocks.
The syntax of multiple capture blocks is as follows:
Try {// program code} catch (exception type 1 Abnormal variable name 1) {// program code} catch (exception type 2 abnormal variable name 2) {// program code} catch (exception type 2 abnormal variable name 2) {// program code}
The above code segment contains three catch blocks.
You can add any number of catch blocks after the try statement.
If exceptions occur in the protection code, the exception is thrown to the first catch Block.
If the data type of the thrown exception matches predictiontype1, it will be captured here.
If it does not match, it will be passed to the second catch Block.
Until the exception is caught or all catch blocks are passed.
Instance
This instance shows how to use multiple try/catch methods.
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 keywords:
If a method does not capture a check exception, 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 captured.
The following method declaration 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}
One method can declare that multiple exceptions are thrown, and multiple exceptions are 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 code block that is executed after the try code block.
No matter whether an exception occurs or not, the code in the finally code block is always executed.
In the finally code block, you can run statements of the final nature such as the cleanup type.
The finally code block appears at the end of the catch code block. The syntax is as follows:
Try {// program code} catch (exception type 1 Abnormal variable name 1) {// program code} catch (exception type 2 abnormal variable name 2) {// program code} finally {// program code}
Instance
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 above example compilation and running results are as follows:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3First element value: 6The finally statement is executed
Note the following:
- Catch cannot exist independently of try.
- Adding finally blocks after try/catch is not mandatory.
- After try code, neither catch Block nor finally block can be found.
- No code can be added between try, catch, and finally blocks.
Declared custom exception
You can customize exceptions in Java. Note the following when writing your own exception classes.
- All exceptions must be a subclass of Throwable.
- If you want to write a checking Exception class, you must inherit the Exception class.
- If you want to write a runtime exception class, you must inherit the RuntimeException class.
You can define your own exception classes as follows:
class MyException extends Exception{}
Only the Exception class created by the Exception class is the checking Exception class.
The following InsufficientFundsException class is a user-defined Exception class that inherits from Exception.
An exception class, like any other class, contains variables and methods.
Instance
// File name: InsufficientFundsException. javaimport java. io. *; public class InsufficientFundsException extends Exception {private double amount; public InsufficientFundsException (double amount) {this. amount = amount;} public double getAmount () {return amount ;}}
To demonstrate how to use our custom exception classes,
The following CheckingAccount class contains a withdraw () method that throws an InsufficientFundsException exception.
// File name CheckingAccount. javaimport 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.
// File name BankDemo. javapublic 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 ();}}}
Compile the above three files and run the BankDemo program. The result is as follows:
Depositing $500...Withdrawing $100...Withdrawing $600...Sorry, but you are short $200.0InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13)
General exceptions
Two types of exceptions and errors are defined in Java.
- JVM (JavaVirtual Machine)Exception:Exceptions or errors thrown by JVM. For example: NullPointerException class, ArrayIndexOutOfBoundsException class, And ClassCastException class.
- Program-level exceptions:Exceptions thrown by programs or API programs. For example, the IllegalArgumentException class and the IllegalStateException class.