Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java exception handling


May 10, 2021 Java


Table of contents


What is an exception?

When a program runs, an unexpected event occurs that prevents the program from executing as normal as the programmer expects, which is an exception. W hen an exception occurs, is the program self-perishing, exiting the termination immediately, or output error to the user? O r in C- style: with function return value as execution state? I n Java, the error that occurs when Java is compiled or run or runs.

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

For example, if your code is missing a half sign, the result of running out is an error java.lang.Error, and if you use System.out.println (11/0), you throw an exception to java.lang.ArithmeticException because you do a division of 0.

Exceptions occur for a number of reasons, often consisting of the following categories:

  • The user entered illegal data.

  • The file to be opened does not exist.

  • The connection is interrupted while the network is communicating, 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. -

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

  • Checkable exceptions: The most representative checkable exceptions are caused by user errors or problems that programmers cannot foresee. For example, when you want to open a nonexistent file, an exception occurs that cannot be simply ignored at compile time.

  • Run-time exceptions: Run-time exceptions are exceptions that may be avoided by programmers. In contrast to checking exceptions, run-time exceptions can be ignored at compile time.

  • Error: The error is not an exception, but a problem out of programmer control. E rrors are often ignored in code. For example, when the stack overflows, an error occurs that they can't be checked for in compilation.


The hierarchy of the Exception class

All exception classes are sub-classes inherited from the java.lang.Exception class.

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

Java programs typically do not catch errors. Errors typically occur in the event of a critical failure and are outside the scope of Java program processing.

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

For example, JVM memory overflows. In general, programs do not recover from errors.

Exception classes have two main sub-classes: the IOException class and the RuntimeException class.

Java exception handling

In Java's built-in classes (as explained next), there are most commonly used checkable and non-checking exceptions.


Java has a built-in exception class

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

The sub-classes of the standard runtime exception class are the most common exception classes. Because java.lang packages are 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 individual class libraries, and the following table lists Java's non-checking exceptions.

Abnormal Describe
ArithmeticException Throws an exception when it occurs. For example, when an integer is divided by zero, an instance of this class is thrown.
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 an object of the wrong type is tried to be stored in an array of objects.
ClassCastException The exception is thrown when an attempt is made to cast an object to a sub-class that is not an instance.
IllegalArgumentException The thrown exception indicates that an illegal or incorrect argument was passed to the method.
IllegalMonitorStateException An exception thrown indicates that a thread has tried to wait for the object's monitor, or that it has tried to notify other monitors that are waiting for the object without specifying a monitor itself.
IllegalStateException The signal generated when the 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 request operation.
IllegalThreadStateException The thread did not throw an exception when it was in the appropriate state required by the request operation.
IndexOutOfBoundsException Indicates that a sort index, such as sorting arrays, strings, or vectors, is thrown out of range.
NegativeArraySizeException If the application tries to create an array of negative sizes, the exception is thrown.
NullPointerException Throws the exception when the application tries to null where it needs the object
NumberFormatException The exception is thrown when an application tries 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 indicates a security violation.
StringIndexOutOfBoundsException This exception is String the String method, indicating that the index is either negative or out of the size of the string.
UnsupportedOperationException The exception is thrown when the requested operation is not supported.

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

Abnormal Describe
ClassNotFoundException When the application tries to load a class, the class cannot be found and the exception is thrown.
CloneNotSupportedException The exception is Object when clone class is called to clone an Cloneable class cannot implement the Cloneable interface.
IllegalAccessException When a class is denied access, the exception is thrown.
InstantiationException The exception is Class 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 One thread was interrupted by another thread and the exception was thrown.
NoSuchFieldException The requested variable does not exist
NoSuchMethodException The requested method does not exist

The exception method

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

Serial number Methods and instructions
1 public String getMessage()
Returns more information about the exception that occurred. This message was initialized in the constructor of the Trowable class.
2 public Throwable getCause()
Returning a Throwable object represents the cause of the exception.
3 public String toString()
The result of using getMessage() returns the serial name of the class.
4 public void printStackTrace()
Print the toString() result and stack hierarchy to System.err, which is the error output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array that contains the stack hierarchy. Elements labeled 0 represent the top of the stack, and the last element represents the bottom of the stack for method calls.
6 public Throwable fillInStackTrace()
Fill the Trowable object stack hierarchy with the current call stack hierarchy and add it to any previous information at the stack level.

Catch an exception

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

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

try
{
   // 程序代码
}catch(ExceptionName e1)
{
   //Catch 块
}

The Catch statement contains a declaration to capture the type of exception. When an exception occurs in the protection block, the catch block behind the try is checked.

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

Instance

In the following example, an array of two elements is declared, and an exception is thrown when the code tries to access the third element of the array.

// 文件名 : 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 above code compiles and runs the output as follows:

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

Multiple capture blocks

A try block followed by multiple catch blocks of code is called multi-capture.

The syntax for multiple capture blocks is as follows:

 try{
    // 程序代码
 }catch(异常类型1 异常的变量名1){
    // 程序代码
 }catch(异常类型2 异常的变量名2){
    // 程序代码
 }catch(异常类型2 异常的变量名2){
    // 程序代码
 }

The snippet above contains three 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 that throws the exception matches ExceptionType1, it is caught here.

If it does not match, it is passed to the second catch block.

So until the exception is caught or passes through all catch blocks.

Instance

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 keywords:

If a method does not catch a checking exception, the method must use the throws keyword to declare. 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 exception:

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 declare that multiple exceptions are thrown, separated by commas.

For example, the following method claims throw RemoteException and UnderFundsException:

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

The final keyword

The final keyword is used to create blocks of code that are executed after try blocks.

The code in the final block is executed regardless of whether an exception occurs or not.

In the final block of code, you can run statements such as cleanup types that are of a post-rehabilitation nature.

The final block of code appears at the end of the catch block, with the following syntax:

 try{
    // 程序代码
 }catch(异常类型1 异常的变量名1){
    // 程序代码
 }catch(异常类型2 异常的变量名2){
    // 程序代码
 }finally{
    // 程序代码
 }

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 examples compile and run as follows:

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

Note the following:

  • Catch cannot exist independently of try.

  • Adding a final block after try/catch is not mandatory.

  • Try code cannot be followed by neither catch blocks nor final blocks.

  • No code can be added between try, catch, finally blocks.


Declare a custom exception

In Java you can customize exceptions. H ere are a few things to keep in mind when writing your own exception classes.

  • All exceptions must be sub-classes of Throwable.

  • If you want to write a check exception class, you need to inherit the Exception class.

  • If you want to write a run-time exception class, you need to inherit the RuntimeException class.

You can define your own exception classes like this:

class MyException extends Exception{
}

Exception classes created by inheriting only the Exception class are check-checking exception classes.

The following UnderFundsException class is a user-defined exception class that inherits from Exception.

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

Instance

// 文件名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 classes,

Include an option() method in the CheckingAccount class below to throw an UnderFundsException 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 $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 program BankDemo, with the following results:

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)

A generic exception

Two types of exceptions and errors are defined in Java.

  • JVM (Java Virtual Machine) Exception: An exception or error thrown by JVM. For example: NullPointerException类 ArrayIndexOutOfBoundsException类 ClassCastException类

  • Program-level exception: An exception thrown by a program or API program. Examples IllegalArgumentException类 IllegalStateException类

After completing this tutorial, it is recommended that you take a hands-on exercise to reinforce what you've learned: Click to get into action