Exceptions are some errors in a program, but not all errors are exceptions, and errors can sometimes be avoided.

For example, if your code is missing a semicolon, the result is java.lang.Error; If you use the System. The out. Println (11/0), then you because you do with zero divisor, throws Java. Lang. ArithmeticException abnormalities.

Exceptions can occur for many reasons, usually including the following categories:

  • The user entered illegal data.
  • The file to open does not exist.
  • The connection is down during network communication, or the JVM runs out of memory.

Some of these exceptions are caused by user error, some by programming errors, and some by physical errors. – \

To understand how Java exception handling works, you need to understand three types of exceptions:

  • Checking exceptions: The most representative checking exceptions are those caused by user errors or problems that the programmer could not have foreseen. For example, when trying to open a nonexistent file, an exception occurs that cannot simply be ignored at compile time.
  • Runtime exceptions: Runtime exceptions are exceptions that can be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.
  • Errors: Errors are not exceptions, but problems outside the programmer’s control. Errors are generally ignored in code. For example, when a stack overflow occurs, an error occurs that is not detected at compile time.

The hierarchy of the Exception class

All Exception classes are subclasses inherited from the java.lang.Exception class.

The Exception class is a subclass of Throwable. In addition to the Exception class, Throwable has a subclass Error.

Java programs generally do not catch errors. Errors typically occur during serious failures that are outside the scope of Java programs to handle.

Error is used to indicate errors in the runtime environment.

For example, the JVM runs out of memory. Generally, programs do not recover from errors.

Exception classes have two main subclasses: IOException and RuntimeException.

Within the Java built-in classes (described next), there are most common checking and non-checking exceptions.


Java built-in exception classes

The Java language defines several exception classes in the java.lang standard package.

A subclass of the standard runtime exception class is the most common exception class. Because the java.lang package is loaded into all Java programs by default, most exceptions inherited from runtime exception classes can be used directly.

Java also defines a number of other exceptions based on each class library. The following table lists Java’s non-checking exceptions.

abnormal describe
ArithmeticException Throws this exception when an exception condition occurs. For example, an instance of this class is thrown when an integer is “divided by zero”.
ArrayIndexOutOfBoundsException An exception thrown when an array is accessed with an invalid index. If the index is negative or greater than or equal to the array size, it is an invalid index.
ArrayStoreException An exception thrown when attempting to store an object of the wrong type into an array of objects.
ClassCastException This exception is thrown when an attempt is made to cast an object to a subclass that is not an instance.
IllegalArgumentException The exception thrown indicates that an invalid or incorrect argument was passed to the method.
IllegalMonitorStateException An exception thrown indicates that a thread has attempted to wait for an object’s monitor or has attempted to notify other monitors that are waiting for an object without specifying a 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 proper state required by the request operation.
IllegalThreadStateException An exception thrown when the thread is not in the proper state required by the requested operation.
IndexOutOfBoundsException Thrown to indicate that a sort index (such as sorting an array, string, or vector) is out of range.
NegativeArraySizeException This exception is thrown if the application tries to create an array of negative size.
NullPointerException When an application tries to use an object where it is needednullThrows the exception
NumberFormatException This exception is thrown when an application tries to convert a string to a numeric type, but the string cannot be converted to the proper format.
SecurityException An exception thrown by the security manager indicating a security violation.
StringIndexOutOfBoundsException This exception byStringMethod, indicating that the index is either negative or beyond the size of the string.
UnsupportedOperationException This exception is thrown when the requested operation is not supported.

The following table lists the checking exception classes defined by Java in the java.lang package.

abnormal describe
ClassNotFoundException The application throws this exception when it tries to load a class and cannot find the corresponding class.
CloneNotSupportedException When callingObjectIn the classcloneMethod to clone an object, but the class of that object cannot be implementedCloneableInterface, the exception is thrown.
IllegalAccessException This exception is thrown when access to a class is denied.
InstantiationException When trying to useClassIn the classnewInstanceMethod creates an instance of a class that cannot be instantiated because the specified class object is an interface or abstract class.
InterruptedException A thread interrupted by another thread throws this exception.
NoSuchFieldException The requested variable does not exist
NoSuchMethodException The requested method does not exist

Abnormal method

The following list is the main methods of the Throwable class:

The serial number Methods and Instructions
1 public String getMessage()Returns detailed information about the exception that occurred. The message is initialized in the constructor of the Throwable class.
2 public Throwable getCause()Return a Throwable object representing the cause of the exception.
3 public String toString()Returns the string name of the class using the result of getMessage().
4 public void printStackTrace()Prints the toString() result and stack hierarchy to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace()Returns an array containing the 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.
6 public Throwable fillInStackTrace()Populates the Throwable object stack hierarchy with the current call stack hierarchy, adding to any previous information in the stack hierarchy.

Catch exceptions

Use the try and catch keywords to catch exceptions. Try /catch blocks are placed where exceptions can occur.

The code in a try/catch block is called protected code, and the syntax for using try/catch is as follows:

Try {// program code}catch(ExceptionName e1) {// catch block}Copy the code

The Catch statement contains the declaration of the type of exception to Catch. When an exception occurs in the protected code block, the catch block after the try is checked.

If an exception occurs that is contained in a catch block, the exception is passed to that catch block, just as an argument is passed to a method.

The instance

The following example declares an array with two elements and raises an exception when the code attempts to access the third element of the array.

// 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"); }}Copy the code

The output of the above code is as follows:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Copy the code

Multiple capture block

A try block followed by multiple catch blocks is called multiple catch.

The syntax for multiple capture blocks looks like this:

Try {// code}catch(1){// code}catch(2){// code}catch(2){// code}Copy the code

The code snippet above contains three catch blocks.

You can add any number of catch blocks after a try statement.

If an exception occurs in the protected 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.

This is done until the exception is caught or passes all catch blocks.

The instance

This example shows how to use multiple tries/catches.

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;
}
Copy the code

Throws /throw keyword:

If a method does not catch a checking exception, the method must be declared using the THROWS keyword. Throws the keyword 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
}
Copy the code

A method can declare to throw multiple exceptions separated by commas.

For example, the following method statement and throw RemoteException InsufficientFundsException:

import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}
Copy the code

Finally the keyword

The finally keyword is used to create a block of code that executes after the try block.

Code ina finally code block is always executed whether or not an exception occurs.

In the finally code block, you can run statements of the cleanup nature, such as cleanup types.

A finally block appears at the end of a catch block, with the syntax:

// finally{// finally{// finally{// finally}Copy the code

The 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"); }}}Copy the code

The compilation and running results of the above examples are as follows:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Copy the code

Note the following:

  • A catch cannot exist independently of a try.
  • It is not mandatory to add a finally block after a try/catch.
  • You cannot have a try code without a catch block or a finally block.
  • No code can be added between try, catch, and finally blocks.

Declare a custom exception

In Java you can customize exceptions. Here 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 checking Exception class, you need to inherit the Exception class.
  • If you want to write a run-time exception class, you need to extend the RuntimeException class.

You can define your own exception class as follows:

class MyException extends Exception{
}
Copy the code

Exception classes created by inheriting only the Exception class are checking Exception classes.

The following InsufficientFundsException class is a user-defined Exception classes, it inherits from Exception.

An exception class, like any other class, contains variables and methods.

The instance

/ / 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; }}Copy the code

To show how to use our custom exception class,

Below CheckingAccount class contains a withdraw () method throws an InsufficientFundsException anomalies.

// 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; }}Copy the code

The BankDemo program below demonstrates how to call the deposit() and withdraw() methods of the CheckingAccount class.

Java public class BankDemo {public static void main(String [] args) {CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..." ); C.d eposit (500.00); try { System.out.println("\nWithdrawing $100..." ); C.w ithdraw (100.00); System.out.println("\nWithdrawing $600..." ); C.w ithdraw (600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); }}}Copy the code

Compile the above three files and run the program BankDemo, resulting in something like this:

Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, But you are short of $200.0 InsufficientFundsException at CheckingAccount. Withdraw the at (CheckingAccount. Java: 25) BankDemo.main(BankDemo.java:13)Copy the code

General exception

There are two types of exceptions and errors defined in Java.

  • JVM(Java Virtual Machine) exception: An exception or error thrown by the JVM. For example: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException class.
  • Program-level exception: An exception thrown by a program or API program. Examples include the IllegalArgumentException class and the IllegalStateException class.