Java Basics - exceptions

Keywords: Java Back-end

Note: the data comes from Blue bridge cloud course( https://www.lanqiao.cn/ ) , interested partners can go to the official website to learn. Here is the information compiled by Xiaobian after his study. If there is any error, please leave a message for discussion. Thank you!

summary

Exception refers to all kinds of unexpected conditions that occur during the operation of the program. Are derived from the Throwable class, which inherits directly from the Object class.

classification

Error

Internal system errors. Such errors are handled by the system, and the program itself does not need to capture and handle them.

Exception

Exceptions that can be handled.

RuntimeException

	Exceptions that can or cannot be caught.
  • Bad type conversion
  • Array access out of bounds
  • Access null pointer
  • Arithmetic anomaly

Generally speaking, RuntimeException is a problem with code logic.

Non RuntimeException

  • Checked Exception
    • Open a file that does not exist
    • No class with the specified name was found
    • Operation file exception

It must be handled by try catch or throw and handed over to the upper caller.

Other classes that inherit Exception

It must be caught, and the exceptions thrown by these methods are usually described in the API document.

Declaration and throw

grammar

throw new Exception class();

Throws is used to declare exceptions, indicating the exceptions that the method may throw. If the declared exception includes a checked exception, the caller must catch and handle the exception or use throws to continue throwing up. Throws is located in front of the method body. It is used between multiple exceptions for segmentation.

import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author : yingH
 * @create : 2021-12060:38
 * @details :
 */
public class ThrowsTest {
    public static void main(String[] args) throws  FileNotFoundException {
        //The caller of the method catches the exception or continues to throw it up
        throwsTest();
    }
    public static void throwsTest() throws FileNotFoundException {
        new FileInputStream("/home/shiyanlou/com.txt");
    }
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author : yingH
 * @create : 2021-12060:38
 * @details :
 */
public class ThrowsTest {
    public static void main(String[] args) throws  FileNotFoundException {
        //The caller of the method catches the exception or continues to throw it up
        throwsTest();
    }
    public static void throwsTest() throws FileNotFoundException {
        new FileInputStream("/home/shiyanlou/com.txt");
    }
}

==>
Exception in thread "main" java.io.FileNotFoundException: \home\shiyanlou\com.txt (The system cannot find the specified path.)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:93)
	at ThrowsTest.throwsTest(ThrowsTest.java:15)
	at ThrowsTest.main(ThrowsTest.java:12)


Catch exception

try and catch statement blocks are used to catch exceptions, and finally is sometimes used.

Try statement blocks are essential. Catch and finally statement blocks can be selected according to the situation. You can put the statements with possible errors or problems into the try statement block, put the statements to be executed after the exception into the catch statement block, and the statements placed in the finally statement block will be executed regardless of whether the exception occurs or not.

/**
 * @author : yingH
 * @create : 2021-12060:45
 * @details :
 */
public class CatchException {
    public static void main(String[] args) {
        try {
            System.out.println("Hello TryBlock");
            //Declaring an empty object triggers "class found no exception"
            Class<?>tempclass=Class.forName("");
            System.out.println("Bye try");

        } catch (ClassNotFoundException e) {
            System.out.println("Hello catchblock");
            //Print error message and error point
            e.printStackTrace();
            System.out.println("Bye catchBlock");
        }finally {
            System.out.println("Hello FinallyBlock");
        }
    }
}

==>
Hello TryBlock
Hello catchblock
Bye catchBlock
Hello FinallyBlock
java.lang.ClassNotFoundException: 
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at CatchException.main(CatchException.java:11)

Catch multiple exceptions

In a piece of code, many different exceptions may be thrown for various reasons. For different exceptions, we want to handle them in different ways instead of using the same way in general. In this case, exception matching can be used. When the corresponding exception is matched, the subsequent exceptions will not be matched.

import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author : yingH
 * @create : 2021-12060:53
 * @details :
 */
public class MultipleCapturesDemo {
    public static void main(String[] args) {
        try {
            new FileInputStream("");
        }catch (FileNotFoundException e){
            System.out.println("IO exception occurred");
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("Other exceptions occurred");
        }
    }
}
==>
IO exception occurred

When handling exceptions, it is not required that the thrown exception exactly matches the exception declared by catch, and the object of the subclass can also match the handler of the parent class. For example, exception A inherits from exception B. when handling multiple exceptions, you must put exception A before exception B. If exception B is placed before exception A, it will always match exception B, exception A will never be executed, and the compiler will report an error.

Custom exception

Just let it inherit Exception or its subclasses. When customizing Exception classes, it is recommended to provide both parameterless constructors and constructors with string parameters

/**
 * @author : yingH
 * @create : 2021-12060:58
 * @details : MyAriException.java
 */
public class MyAriException  extends ArithmeticException{
    public MyAriException() {
    }

    public MyAriException(String msg) {
        super(msg);
    }

}

import java.util.Arrays;

/**
 * @author : yingH
 * @create : 2021-12061:02
 * @details :ExceptionTest.java
 */
public class ExceptionTest {
    public static void main(String[] args) {
        int[] arr = new int[5];
        Arrays.fill(arr,5);
        for (int i = 4; i >-1 ; i--) {
            if (i==0)
                throw  new MyAriException("There is an exception occured");
            System.out.println("array[" + i + "]/" + i + "=" + arr[i] / i);
        }
    }
}

==>
array[4]/4=1
array[3]/3=1
array[2]/2=2
array[1]/1=5
Exception in thread "main" MyAriException: There is an exception occured
	at ExceptionTest.main(ExceptionTest.java:14)

Exception stack

import java.io.FileNotFoundException;

/**
 * @author : yingH
 * @create : 2021-12061:08
 * @details :Exception stack
 */
public class ExceptionStackTrace {
    public static void meth1(){
        meth2();
    }

    public static void meth2(){
        throw new NullPointerException();
    }

    public static void main(String[] args) {
        meth1();
    }
}

==>
Exception in thread "main" java.lang.NullPointerException
	at ExceptionStackTrace.meth2(ExceptionStackTrace.java:14)
	at ExceptionStackTrace.meth1(ExceptionStackTrace.java:10)
	at ExceptionStackTrace.main(ExceptionStackTrace.java:18)

By comparing the above exception stack trace with the calling process of our method, it can be concluded that in the exception information, the statement closest to throwing the exception is printed first, followed by the method calling the method until the method called at the beginning. From the bottom up, we can get the track of the program.

Posted by ajsuk on Sun, 05 Dec 2021 15:08:01 -0800