Java learning road-exception handling

Java learning road-exception handling

Overview

Errors may occur when running Java programs, but not all errors are exceptions.

A robust program must be able to handle all kinds of errors!

There are two types of errors in Java programs:

ERROR

ERROR refers to a serious program problem that the Java virtual machine cannot solve. For example: JVM system internal errors, resource exhaustion errors, etc. Under normal circumstances, errors cannot be resolved by targeted code.

Exception

Exception refers to other general problems caused by programming errors or other accidental factors. These problems can be solved with targeted code.

E.g:

  • Null pointer access
  • Array subscript out of bounds
  • Network Error

One, catch the exception

To handle exceptions, you must first be able to catch exceptions.

In Java, any statement that may throw an exception can be try ... catchcaught. Put the statement that may occur in the exception try { ... }, and then use the catchcapture corresponding Exceptionand its subclasses.

A try code block can be followed by multiple catch code blocks to handle various exceptions. After the JVM catches the exception, it will match the catchstatement from top to bottom . catchAfter a certain match is reached, the catchcode block will be executed , and then no further matching will be continued.

finallyKeyword is used to create a tryblock of code back block. Regardless of whether an exception occurs, the finallycode in the code block will always be executed. In the finallycode block, clean type and the like can run ending statements rehabilitation nature.

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

Example

import java.util.InputMismatchException;
import java.util.Scanner;

public class Demo {
    
    
    public static void main(String[] args)  {
    
    
        try {
    
    
            int res, divisor;
            Scanner scan = new Scanner(System.in);

            divisor = scan.nextInt();
            res = 10 / divisor;
        } catch (ArithmeticException e) {
    
    
            System.out.println(e);
            System.out.println("除数不能为0");
        } catch (InputMismatchException e1) {
    
    
            System.out.println(e1);
            System.out.println("输入出现问题");
        } finally {
    
    
            System.out.println("异常处理完毕");
        }
    }
}

Two, throw an exception

When a method throws an exception, if the current method does not catch the exception, the exception will be thrown to the upper layer to call the method until a caught one try ... catchis encountered . This is the propagation of the exception.

In Java programs, you can use throwthe keyword active throws an exception in the case of the method in the initiative thrown in general use in the function declaration throwskeywords that may be thrown clear written.

import java.util.InputMismatchException;
import java.util.Scanner;

public class Demo {
    
    
    public static int test(int dividend, int divisor) throws ArithmeticException {
    
    
        if (divisor == 0) {
    
    
            throw new ArithmeticException();
        } else {
    
    
            return dividend / divisor;
        }
    }

    public static void main(String[] args)  {
    
    
        try {
    
    
            int res;
            Scanner scan = new Scanner(System.in);

            res = Demo.test(scan.nextInt(), scan.nextInt());
            System.out.println(res);
        } catch (ArithmeticException e) {
    
    
            System.out.println(e);
            System.out.println("除数不能为0");
        } catch (InputMismatchException e1) {
    
    
            System.out.println(e1);
            System.out.println("输入出现问题");
        } finally {
    
    
            System.out.println("异常处理完毕");
        }
    }
}

Three, custom exception

The Java standard library defines a large number of common exceptions, but sometimes the exceptions of the Java standard library are not enough for us to use. At this time, we can choose to define our own exceptions to handle our actual business needs.

Note the following points for custom exception classes:

  • All exceptions must be Throwablesubclasses;
  • If you want to write a checked exception class, you need to inherit Exceptionthe class;
  • Exception class if you want to write a run, we need to inherit RuntimeExceptionthe class.

Example

import java.util.InputMismatchException;
import java.util.Scanner;

public class Demo {
    
    
    public static int test(int dividend, int divisor) throws ArithmeticException {
    
    
        if (divisor == 0) {
    
    
            throw new DivisorIsZero();
        } else {
    
    
            return dividend / divisor;
        }
    }

    public static void main(String[] args)  {
    
    
        try {
    
    
            int res;
            Scanner scan = new Scanner(System.in);

            res = Demo.test(scan.nextInt(), scan.nextInt());
            System.out.println(res);
        } catch (ArithmeticException e) {
    
    
            System.out.println(e);
            System.out.println("除数不能为0");
        } catch (InputMismatchException e1) {
    
    
            System.out.println(e1);
            System.out.println("输入出现问题");
        } finally {
    
    
            System.out.println("异常处理完毕");
        }
    }
}

class DivisorIsZero extends ArithmeticException {
    
    
    public DivisorIsZero() {
    
    
        System.out.println("除数为0");
    }
}

Four, assertion

Assertion is a way of debugging a program. In Java, assertkeywords are used to implement assertions.

It will be thrown when the assertion fails AssertionError, causing the program to end and exit. Therefore, assertions cannot be used for recoverable program errors and should only be used during development and testing.

Note: Assertions are not turned on by default in IDEA! We need to manually turn on the assertion!

import java.util.Scanner;

public class Demo {
    
    
    public static void main(String[] args)  {
    
    
        try {
    
    
            int res, dividend, divisor;
            Scanner scan = new Scanner(System.in);

            dividend = scan.nextInt();
            divisor = scan.nextInt();

            assert divisor != 0 : "divisor must != 0";

            System.out.println("divisor");
            res = dividend / divisor;
            System.out.println(res);
        } catch (AssertionError e) {
    
    
            System.out.println("除数不能为0");
        } finally {
    
    
            System.out.println("异常处理完毕");
        }
    }
}

Five, common exceptions

Common exceptions defined by the Java standard library include:

Exception
├─ RuntimeException
│  │
│  ├─ NullPointerException
│  │
│  ├─ IndexOutOfBoundsException
│  │
│  ├─ SecurityException
│  │
│  └─ IllegalArgumentException
│     │
│     └─ NumberFormatException
├─ IOException
│  │
│  ├─ UnsupportedCharsetException
│  │
│  ├─ FileNotFoundException
│  │
│  └─ SocketException
├─ ParseException
├─ GeneralSecurityException
├─ SQLException
└─ TimeoutException
Exception class Abnormal
ArithmeticException The exception caused by the division by 0
ArrayStoreException Exception caused by insufficient array storage space
ClassCastException When an object is classified into a certain class, but in fact the object is not created by this class or its subclasses, it will cause an exception
IllegalMonitorStateException Exception caused by monitor status error
NegativeArraySizeException If the array length is negative, an exception occurs
NullPointerException An exception occurs when the program tries to access an element in an empty array or access a method or variable in an empty object
SecurityException Due to access to pointers that should not be accessed, security problems cause exceptions
IndexOutOfBoundsExcention Array subscript out of range or string access out of range cause an exception
IOException The file is not found, not opened, or the I/O operation cannot be performed, causing an exception
ClassNotFoundException The class or interface with the specified name was not found, causing an exception
CloneNotSupportedException An object in the program references the clone method of the Object class, but this object is not connected to the Cloneable interface, which causes an exception
InterruptedException When a thread is in a waiting state, another thread interrupts this thread, causing an exception
NoSuchMethodException The called method was not found, causing an exception
IllegalAccessExcePtion Trying to access a non-public method
StringIndexOutOfBoundsException The access string number is out of range, causing an exception
ArrayIdexOutOfBoundsException Access array element subscript out of bounds, causing an exception
NumberFormatException The character's utf-8 code data format is wrong, causing an exception
IllegalThreadException The thread calls a method and is in an inappropriate state, causing an exception
FileNotFoundException The specified file was not found causing an exception
EOFException The end of the file causes an exception when the input operation is not completed

Guess you like

Origin blog.csdn.net/qq_43580193/article/details/112661654