Java foundation 20 Java exception handling

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 that the error is Java lang.Error; If you use system out. Println (11 / 0), then you will throw Java because you use 0 as the divisor Exception of lang.arithmeticexception.

There are many reasons for exceptions, usually including the following categories:
The user entered illegal data.
The file to open does not exist.
The connection is interrupted during network communication, or the JVM memory overflows.

Some of these exceptions are caused by user errors, some are caused by program errors, and others are caused by physical errors.

You need to master the following three types of exceptions:
Checking exceptions: the most representative checking exceptions are those 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: the error is not an exception, but a problem out of the control of the programmer. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.

1, Hierarchy of Exception class

All exception classes are from Java A subclass inherited by the lang.exception class.
The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable also has a subclass Error.

Java programs usually do not catch errors. Errors usually occur in the case of serious failures, which are outside the scope of Java program processing.

Error is used to indicate an error in the runtime environment.

2, Java built-in exception class

The Java language defines some exception classes in Java Lang standard package.

Subclasses of the standard runtime exception class are the most common exception classes. Due to 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 following table lists Java's non checking exceptions.

abnormal describe
ArithmeticException Arithmetic exception: this exception is thrown when the operation condition of the exception occurs. For example, when an integer is "divided by zero", an instance of this class is thrown.
ArrayIndexOutOfBoundsException Array overflow exception, 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 This exception is thrown when an attempt is made to cast an object to a subclass that is not an instance.
IllegalArgumentException When an exception is thrown, it indicates that an illegal or incorrect parameter has been passed to the method.
IllegalMonitorStateException The 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 Indicates that 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 Null pointer exception, which is thrown when the 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 to indicate that the index is either negative or exceeds the size of the String.
UnsupportedOperationException This exception is thrown when the requested operation is not supported.

The following table lists the Java definitions in Java Lang package.

abnormal describe
ClassNotFoundException When the application tries to load a class, it cannot find the corresponding class and throws the exception.
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

3, Abnormal method

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

public String getMessage()
Returns details 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 toString() results and stack hierarchy to system Err, the error output stream.

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.

public Throwable fillInStackTrace()
Fill the Throwable object stack hierarchy with the current call stack hierarchy and add it to any previous information in the stack hierarchy.

4, Catch exception

Use the try and catch keywords to catch exceptions. try/catch code blocks are placed where exceptions can 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 try will be 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.

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");
   }
}

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

5, Multiple capture block

The case where a try code block is followed by multiple catch code blocks is called multiple capture.

The syntax of multiple capture blocks is as follows:

try{
   // Program code
}catch(Variable name of exception type 1){
  // Program code
}catch(Variable name of exception type 2){
  // Program code
}catch(Variable name of exception type 2){
  // Program code
}

The above code snippet contains three catch blocks.
You can add any number of catch blocks after a 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 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 passed through all catch blocks.

try {
    file = new FileInputStream(fileName);
    x = (byte) file.read();
} catch(FileNotFoundException f) { // Not valid!
    f.printStackTrace();
    return -1;
} catch(IOException i) {
    i.printStackTrace();
    return -1;
}

6, throws/throw keyword:

If a method does not catch a checking 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 throw an exception using the throw keyword, whether it is newly instantiated or just caught.

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

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

7, finally keyword:

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

Whether or not an exception occurs, the code in the finally code block will always be executed.

In the finally code block, you can run closing statements such as cleanup types

finally, the code block appears at the end of the catch code block. The syntax is as follows:

try{
  // Program code
}catch(Variable name of exception type 1){
  // Program code
}catch(Variable name of exception type 2){
  // Program code
}finally{
  // Program code
}
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");
    }
  }
}

Note the following:

catch cannot exist independently of try.
Adding a finally block after try/catch is not mandatory.
try code cannot be followed by neither catch nor finally blocks.
No code can be added between try, catch and finally blocks.

8, Declare custom exception:

In Java, you can customize exceptions. When writing your own exception class, you need to keep the following points in mind.
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.

Define your own exception class:

class MyException extends Exception{
}

The Exception class created by inheriting only the Exception class is the checking Exception class.
An exception class, like any other class, contains variables and methods.

// File name insufficientfundsexception java
import java.io.*;
 
//Custom Exception class, inheriting Exception class
public class InsufficientFundsException extends Exception
{
  //The amount here is used to store the money that is lacking when there is an exception (when the withdrawal is more than the balance)
  private double amount;
  public InsufficientFundsException(double amount)
  {
    this.amount = amount;
  } 
  public double getAmount()
  {
    return amount;
  }
}
// File name checkingaccount java
import java.io.*;
 
//Such simulated bank accounts
public class CheckingAccount
{
  //Balance is the balance and number is the card number
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
  //Method: save money
   public void deposit(double amount)
   {
      balance += amount;
   }
  //Method: withdraw money
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
  //Method: return balance
   public double getBalance()
   {
      return balance;
   }
  //Method: return card number
   public int getNumber()
   {
      return number;
   }
}
//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();
      }
    }
}

9, 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. For example: NullPointerException
Class, ArrayIndexOutOfBoundsException class, ClassCastException class.
Program level exception: an exception thrown by a program or API program. For example, IllegalArgumentException
Class, IllegalStateException class.

Tags: Java Exception

Posted by djanim8 on Thu, 12 May 2022 15:12:21 +0300