当前位置:网站首页>Introduction to exceptions

Introduction to exceptions

2022-06-21 06:49:00 naoguaziteng

Objective record

1. Abnormal system

2. Abnormal operation period

Abnormal operation period

Handling runtime exceptions

3. Compile time exception

Handle compile time exceptions

4.throw And throws The difference between

5. Common exceptions

7. Custom exception

8. Unusual notes


1. Abnormal system

 

         Exception is Java An error in the execution of a program .Throwable Is the parent of all exceptions . Throwable It can be divided into two categories Error Classes and Exception class ,Error Class exceptions are difficult or even impossible for programmers to catch and handle ,Exception Class exceptions can be captured and handled !Exception Class exceptions are composed of compile - time exceptions and run - time exceptions . Compile time exceptions must be handled , Runtime exceptions can be handled or not !

2. Abnormal operation period

Abnormal operation period

         The runtime exception is RuntimeException Classes and subclasses Occurs during operation , It can be solved or not . Abnormal operation period , If we don't capture and process by ourselves , It's up to JVM For default processing .JVM The default way to handle exceptions is to print the stack information of the exception , And then quit JVM. sign out JVM That is, once the program encounters an exception, it will directly end and exit , Even if there is still code after the exception, it will not continue to execute the following code ! Obviously ,JVM The default way of handling exceptions is not friendly , If you want to be more friendly , We can catch exceptions and handle them ourselves .

Handling runtime exceptions

try{                                               // One try There can be many exceptions , The corresponding can be followed by many catch

There may be unexpected code ;

}catch( Types of exceptions that may occur   Variable name ){

The logic of exception handling ;                         // Generally, abnormal information will be printed , I can't help writing , Otherwise, I don't know if something abnormal happens

}finally{

Generally, it is necessary to deal with the aftermath ;                         // For example, close to release some resources

}

         Only when you catch the abnormality can you enter catch In the sentence , If you don't catch it, you won't come in ! And the exceptions can be defined as clearly as possible , Try not to use Exception The catching ! When there are multiple exceptions , The exception type is a juxtaposition relationship , Everyone in front of and behind us is OK ! But if it is an abnormal parent-child relationship , Then the subclass exception needs to be written in front of the parent exception ! and finally Is an optional keyword , That is, not all exceptions are captured and handled finally sentence , And no matter what happens to the release ,finally All the code in !

repair :  printStackTrace();                       How to print detailed exception stack information .

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        int[] arr = {1, 2};
        arr = null;
        try {
            System.out.println(arr.length);
            System.out.println(a / b);
            System.out.println(arr[3]);
        } catch (ArithmeticException e) {
            System.out.println(" Divisor is 0");
            e.printStackTrace(); // Print detailed stack information 
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(" The corner sign is out of bounds ");
            e.printStackTrace(); // Print detailed stack information 
        } catch (NullPointerException e) {
            System.out.println(" Null pointer exception ");
            e.printStackTrace(); // Print detailed stack information 
        } catch (Exception e) {
            System.out.println(" Something is wrong ");
            e.printStackTrace(); // Print detailed stack information 
        }
    }
}

When multiple exceptions occur , The above wording is JDK1.8 After version . Xiaobian has also collected JDK1.7 How to write the version !

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        int[] arr = {1, 2};
        arr = null;

        //jdk1.7 edition 
        try {
            System.out.println(arr.length);
            System.out.println(a / b);
            System.out.println(arr[3]);
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException | NullPointerException e){
            if (e instanceof ArithmeticException){
                ((ArithmeticException) e).printStackTrace();
            }else if (e instanceof ArrayIndexOutOfBoundsException){
                ((ArrayIndexOutOfBoundsException) e).printStackTrace();
            }else if (e instanceof NullPointerException){
                ((NullPointerException) e).printStackTrace();
            }
        }

    }
}

3. Compile time exception

Compile time exception : It happened during compilation , Not RuntimeException And its subclasses , Must be resolved . If the exception is not resolved , The program can't run !

Handle compile time exceptions

Method 1 :throws Throw up , Throw to caller , Who calls who deals with , Be commonly called " Wok "!

public class Test3 {
    public static void main(String[] args) throws ParseException {
        String date="2022-06-02";
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        simpleDateFormat.parse(date);     //parse Method has a compile time exception 
    }
}

  Method 2 : Capture processing ,try{}catch(){}

public class Test3 {
    public static void main(String[] args){
        String date="2022-06-02";
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        try {
            simpleDateFormat.parse(date);     //parse Method has a compile time exception 
        } catch (ParseException e) {
            e.printStackTrace();              // Print information 
        }
    }
}

General throwing main The method , Just don't keep throwing , Again main It is better to capture and dispose of them in the method ! And if there is any exception in the method of the tool class written by yourself , Just throw it out , Let the caller catch and handle exceptions by himself !

4.throw And throws The difference between

throw:    Something happens inside the functional method , The program can't continue to run , When a jump is needed , Just use throw Throw the exception object . Both compile - time and run - time exceptions can be handled !

  • throws
  •          Used after method declaration , With the exception class name
  •          It can be used with multiple exception class names , Separated by commas
  •          Means throw an exception , Handled by the caller of the method
  •         throws Represents a possibility of an exception , These exceptions do not necessarily occur
  • throw
  •          Used in method body , Followed by the exception object name
  •          Only one exception object name can be thrown
  •          This exception object can be a compile time exception object , It can be a runtime exception object
  •          Means throw an exception , Handled by statements inside the method
  •         throw An exception is thrown , perform throw It must have thrown some exception

5. Common exceptions

  • NullPointerException:  Null pointer exception , When operating a null This exception is thrown when the method or property of the . It's a headache , Because it is a runtime exception , You don't need to capture it manually , But this exception will interrupt the program when running .
  • ClassCastException:  Class conversion exception , This exception will be thrown when an instance of this class is converted to this class . If you cast a number into a string, this exception will be reported , It's a runtime exception , No manual capture required .
  • IndexOutOfBoundsException: Index out of range exception , Exceptions often encountered when manipulating a string or array . It's a runtime exception , No manual capture required .
  • ArithmeticException: Arithmetical abnormality , Exception in arithmetic operation of number , As a number divided by 0 It's a mistake . Although this exception is a runtime exception , But you can catch and throw custom exceptions manually .
  • IOException:  IO, namely :Input、Output, We are reading and writing disk files 、 A kind of anomaly often occurs when network content , This exception is a checked exception , Manual capture required .
  • FileNotFoundException: File not found exception , This exception will be thrown if the file does not exist . It's also IOException Subclasses of , It's also checked abnormal , Manual capture required .
  • ClassNotFoundException: Class cannot find exception ,Java An exception often encountered in development , This is thrown when the class is loaded , That is, the specified class cannot be loaded under the classpath . It's a checked exception , Manual capture required .
  • NoSuchMethodException: No exception for this method , Usually occurs when a reflection calls a method , It's a checked exception , Manual capture is required .
  • SQLException: SQL abnormal , Exception occurred while operating the database .
  • OutOfMemoryError: Memory overflow exception , This is not what the program can control Error class , When the memory of the object to be allocated exceeds the current maximum heap memory , Need to resize heap memory (-Xmx) And optimization procedures .

7. Custom exception

In addition to the above exceptions, you can also define your own exceptions , For example, let's withdraw money from the bank , When the balance is insufficient, there will be an abnormal balance shortage , This is the custom exception . Custom exception , You need to create an exception class by yourself , And then put this class into Java In the anomaly system of . Then you can use this exception class .

// Custom exception , Incorporate into Java In the anomaly system of 
public class NoMoneyException extends RuntimeException {
    public NoMoneyException() {
    }

    public NoMoneyException(String message) {
        super(message);
    }
}
public class MyTest {
    public static int money = 200;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(" Please enter your withdrawal amount ");
        int num = sc.nextInt();
        getMoney(num);
    }

    private static void getMoney(int num) {
        if (num <= money) {
            money -= num;
            System.out.println(" Successful withdrawals ");
        } else {
            throw new NoMoneyException(" Lack of balance ");
        }
    }
}

8. Unusual notes

  • When subclasses override parent methods , The parent method did not throw an exception , Subclasses cannot throw exceptions
  • The parent class method throws an exception , Subclasses can throw the same exception as the parent class when overriding the parent class method , You can also not throw
  • The parent class method throws an exception , A subclass can throw an exception when overriding a parent class method , But the exception cannot be larger than the parent class

( Xiaobian is also trying to learn more ! There are many exceptions , I'll add it slowly later !)

Hope to be helpful to friends !!!!

原网站

版权声明
本文为[naoguaziteng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210624100144.html