Java Exception Detailed Explanation

Articles and codes have been archived in [Github warehouse: https://github.com/timerring/java-tutorial] or the public account [AIShareLab] can also be obtained by replying to java .

quick start

Select the code block that may have an exception -> shortcut key ctrl + alt + t-> selecttry-catch

package com.hspedu.exception_;

public class Exception01 {
    
    
    public static void main(String[] args)  {
    
    
        int num1 = 10;
        int num2 = 0;//Scanner();
        //2. 当执行到 num1 / num2 因为 num2 = 0, 程序就会出现(抛出)异常 ArithmeticException
        //3. 当抛出异常后,程序就退出,崩溃了, 下面的代码就不再执行
        //4. 不应该出现了一个不算致命的问题就导致整个系统崩溃
        //5. java 设计者,提供了一个叫异常处理机制来解决该问题
        //如果程序员,认为一段代码可能出现异常/问题,可以使用try-catch异常处理机制来解决,从而保证程序的健壮性
        //将该代码块->选中->快捷键 ctrl + alt + t -> 选中 try-catch
        //6. 如果进行异常处理,那么即使出现了异常,程序可以继续执行
        try {
    
    
            int res = num1 / num2;
        } catch (Exception e) {
    
    
            //e.printStackTrace();
            System.out.println("出现异常的原因=" + e.getMessage());//输出异常信息
        }

        System.out.println("程序继续运行....");

    }
}

Exception introduction

In the Java language, an abnormal situation that occurs during program execution is called an "abnormal". (Syntax errors and logic errors during development are not exceptions)

Abnormal events that occur during execution can be divided into two categories:

1. Error (error): a serious problem that the Java virtual machine cannot solve. Such as: JVM system internal errors, resource exhaustion and other serious situations. For example: StackOverflowError[stack overflow] and OOM(out of memory).

Error is a serious error, the program will crash.

2. Exception: Other general problems caused by programming errors or accidental external factors can be handled with specific codes. For example, null pointer access, trying to read a file that does not exist, network connection interruption, etc., Exception is divided into two categories:

  • runtime exception [exception that occurs when the program is running]
  • Compile-time exceptions [exceptions detected by the compiler during programming]

A list of abnormal system diagrams!

Abnormal System Diagram

Summary of Exception Hierarchy

  1. Exceptions fall into two broad categories, runtime exceptions and compile-time exceptions.
  2. The runtime exception cannot be detected by the compiler. Generally, it refers to a logic error during programming, which is an exception that programmers should avoid. java.lang.RuntimeExceptionThe class and its subclasses are runtime exceptions.
  3. For runtime exceptions, it is not necessary to handle them, because such exceptions are very common, and if they are fully processed, they may affect the readability and operating efficiency of the program.
  4. Compile-time exceptions are exceptions that must be handled by the compiler.

Common Runtime Exceptions

Common runtime exceptions include

  1. NullPointerExceptionnull pointer exception
  2. ArithmeticExceptionmath exception
  3. ArrayIndexOutOfBoundsExceptionArray subscript out of bounds exception
  4. ClassCastExceptiontype conversion exception
  5. NumberFormatExceptionIncorrect number format exception[]

Examples of common runtime exceptions

  1. NullPointerExceptionNull Pointer Exception
    Thrown when an application attempts to use null where an object is expected.
public class NullPointerException_ {
    
    
  public static void main(String[] args) {
    
    

      String name = null; // 空指针出现异常
      System.out.println(name.length());
  }
}
  1. ArithmeticExceptionmath exception

    This exception is thrown when an abnormal operation condition occurs. For example, an instance of this class is thrown when an integer is "divided by zero".

  1. ArrayIndexOutOfBoundsExceptionArray subscript out of bounds exception
    An exception thrown when an illegal index is used to access an array. An index is an illegal index if it is negative or greater than or equal to the size of the array.
  1. ClassCastExceptionType Conversion Exception Thrown
    when an attempt is made to cast an object to a subclass that is not an instance. For example, the following code will generate a ClassCastException.
public class ClassCastException_ {
    
    
  public static void main(String[] args) {
    
    
      A b = new B(); //向上转型
      B b2 = (B)b;//向下转型,这里是OK
      C c2 = (C)b;//这里抛出ClassCastException
  }
}
class A {
    
    }
class B extends A {
    
    }
class C extends A {
    
    }
  1. NumberFormatExceptionIncorrect number format exception This exception is thrown
    when the application tries to convert a string to a numeric type, but the string cannot be converted to the proper format => Using exceptions we can ensure that the input is a number that satisfies the condition.
public class NumberFormatException_ {
    
    
  public static void main(String[] args) {
    
    
      String name = "timerring";
      //将String 转成 int
      int num = Integer.parseInt(name); // 抛出NumberFormatException
      System.out.println(num);
  }
}

compile exception

Compilation exceptions refer to exceptions that must be handled during compilation, otherwise the code cannot be compiled.

Common compilation exceptions

SQLException: When operating the database, an exception may occur in the query table

IOException: An exception occurred when operating a file

FileNotFoundException: When operating a file that does not exist, an exception occurs

ClassNotFoundException: When loading a class, but the class does not exist, an exception will occur

EOFException: Operate the file, reach the end of the file, and an exception occurs

lllegalArguementException: Parameter exception

exception handling

basic introduction

Exception handling is the way an exception is handled when an exception occurs.

The way exceptions are handled

  1. try-catch-finally: The programmer catches the exception that occurs in the code and handles it by himself

  2. throws: Throw the exception that occurs and hand it over to the caller (method) for processing. The top-level handler is the JVM.

schematic diagram

If the programmer does not explicitly handle exceptions, the default is throws.

try-catch exception handling

Description of exception handling in try-catch mode

  1. Java provides try and catch blocks to handle exceptions. The try block is used to contain code that may go wrong. The catch block is used to handle exceptions that occur in the try block. You can have as many try...catch blocks in your program as you want.

  2. basic grammar

try {
    
    
  //可疑代码
  //将异常生成对应的异常对象,传递给catch块
}catch(异常){
    
    
  //对异常的处理
}
//如果没有finally,语法是可以通过

Try-catch way to handle exception details

  1. If an exception occurs, the code behind the exception will not be executed, and it will directly enter the catch block.

  2. If no exception occurs, the code blocks of try are executed sequentially without entering catch.

  3. If you want to execute a certain piece of code regardless of whether an exception occurs (such as closing the connection, releasing resources, etc.)
    , use the following code finally {}

  4. There can be multiple catch statements to catch different exceptions (for different business processing), requiring parent class exceptions
    to follow and subclass exceptions to come first, for example ( Exceptionbehind, NullPointerExceptionbefore), if an exception occurs, only one will be matched catch. (Because if you let capture in the front Exception, it will be useless to write subclass capture later).

    package com.hspedu.try_;
    
    public class TryCatchDetail02 {
          
          
        public static void main(String[] args) {
          
          
            
            //1.如果try代码块有可能有多个异常
            //2.可以使用多个catch 分别捕获不同的异常,相应处理
            //3.要求子类异常写在前面,父类异常写在后面
            try {
          
          
                Person person = new Person();
                //person = null;
                System.out.println(person.getName());//NullPointerException
                int n1 = 10;
                int n2 = 0;
                int res = n1 / n2;//ArithmeticException
            } catch (NullPointerException e) {
          
          
                System.out.println("空指针异常=" + e.getMessage());
            } catch (ArithmeticException e) {
          
          
                System.out.println("算术异常=" + e.getMessage());
            } catch (Exception e) {
          
          
                System.out.println(e.getMessage());
            } finally {
          
          
            }
        }
    }
    
    class Person {
          
          
        private String name = "jack";
        public String getName() {
          
          
            return name;
        }
    }
    
  5. It can be try-finallyused together. This usage is equivalent to not catching exceptions, so the program will
    crash/exit directly. The application scenario is to execute a piece of code, regardless of whether an exception occurs, a certain business logic must be executed.

    public class TryCatchDetail03 {
          
          
        public static void main(String[] args) {
          
          
            /*
            可以进行 try-finally 配合使用, 这种用法相当于没有捕获异常,
            因此程序会直接崩掉/退出。应用场景,就是执行一段代码,不管是否发生异			常,都必须执行某个业务逻辑
             */
            try{
          
          
                int n1 = 10;
                int n2 = 0;
                System.out.println(n1 / n2);
            }finally {
          
          
                System.out.println("执行了finally.."); // 执行完直接退出
            }
            System.out.println("程序继续执行.."); // 不会执行
        }
    }
    

practise

package com.hspedu.try_;

public class TryCatchExercise01 {
    
    
}

class Exception01 {
    
    
    public static int method() {
    
    
        try {
    
    
            String[] names = new String[3];//String[]数组
            if (names[1].equals("tom")) {
    
    //NullPointerException
                System.out.println(names[1]);
            } else {
    
    
                names[3] = "hspedu";
            }
            return 1;
        } catch (ArrayIndexOutOfBoundsException e) {
    
    
            return 2;
        } catch (NullPointerException e) {
    
    //捕获
            return 3; // 但是不从这里返回
        } finally {
    
      // 必须执行,相当于没有异常捕获
            return 4; // 返回4
        }
    }

    public static void main(String[] args) {
    
    
        System.out.println(method()); // 输出4
    }
}
package com.hspedu.try_;

public class TryCatchExercise03 {
    
    
}

class ExceptionExe01 {
    
    
    public static int method() {
    
    
        int i = 1;//i = 1
        try {
    
    
            i++;// i=2
            String[] names = new String[3];
            if (names[1].equals("tom")) {
    
     //空指针
                System.out.println(names[1]);
            } else {
    
    
                names[3] = "hspedu";
            }
            return 1;
        } catch (ArrayIndexOutOfBoundsException e) {
    
    
            return 2;
        } catch (NullPointerException e) {
    
    
            return ++i;  // i = 3 => 保存临时变量 temp = 3;
        } finally {
    
    
            ++i; //i = 4
            System.out.println("i=" + i);// i = 4
        }
    }

    public static void main(String[] args) {
    
    
        System.out.println(method());// 3
    }
}
// 最终输出 i = 4    3

try-catch-finally execution sequence summary

  1. If no exception occurs, all statements in the try block are executed, and the statements in the catch block are not executed. If there is finally, the statements in finally need to be executed.
  2. If an exception occurs, after the exception occurs in the try block, the remaining statements in the try block will not be executed. The statement in the catch block will be executed. If there is finally, the statement in finally needs to be executed at last.

Exercises after class

If the user enters something other than an integer, prompt him to enter repeatedly until he enters an integer

package com.hspedu.try_;

import java.util.Scanner;

public class TryCatchExercise04 {
    
    
    public static void main(String[] args) {
    
    

        //如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止
        //思路
        //1. 创建Scanner对象
        //2. 使用无限循环,去接收一个输入
        //3. 然后将该输入的值,转成一个int
        //4. 如果在转换时,抛出异常,说明输入的内容不是一个可以转成int的内容
        //5. 如果没有抛出异常,则break 该循环
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        String inputStr = "";
        while (true) {
    
    

            System.out.println("请输入一个整数:"); //
            inputStr = scanner.next();
            try {
    
    
                num = Integer.parseInt(inputStr); //这里是可能抛出异常
                break;
            } catch (NumberFormatException e) {
    
    
                System.out.println("你输入的不是一个整数:");
            }
        }

        System.out.println("你输入的值是=" + num);
    }
}

throws exception handling

basic introduction

  1. If a method (when the statement in it is executed) may generate some kind of exception, but it is not sure how to handle this exception, this method should explicitly declare that the exception is thrown, indicating that the method will not handle these exceptions, but by the method. The caller of the method is responsible for processing .
  2. In the method declaration, the throws statement can be used to declare the list of thrown exceptions. The exception type behind throws can be the exception type generated in the method, or its parent class.

Quick Start Case

The exception type behind throws can be the exception type generated in the method (it can also be an exception list, and multiple exceptions are thrown), or it can be its parent class (such as Exception).

package com.hspedu.throws_;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Throws01 {
    
    
    public static void main(String[] args) {
    
    
    }

    public void f2() throws FileNotFoundException,NullPointerException,ArithmeticException {
    
    
        //创建了一个文件流对象
        //1. 这里的异常是一个FileNotFoundException 编译异常
        //2. 使用前面讲过的 try-catch-finally
        //3. 使用throws ,抛出异常, 让调用f2方法的调用者(方法)处理
        //4. throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类(例如 Exception)
        //5. throws 关键字后也可以是 异常列表, 即可以抛出多个异常
        FileInputStream fis = new FileInputStream("d://aa.txt");

    }
}

Precautions and usage details

  1. For compilation exceptions, it must be handled in the program , such as try-catch or throws.

  2. For runtime exceptions, if there is no processing in the program, the default is to handle them in the way of throws (equivalent to a throws XXXException after the method, then go up step by step, and finally the main method may also default to throws, and then it will be handled by the JVM).

  3. When a subclass rewrites the method of the parent class, the rules for throwing exceptions: the method rewritten by the subclass, the type of exception thrown is either the same as the exception thrown by the parent class, or the type of exception thrown by the parent class subtype of .

  4. In the process of throws, if there is a method try-catch, it is equivalent to handling exceptions, so throws are not necessary.

    For example, if a subclass has a compilation exception and throws it using throws, then the parent class must also respond to the exception, or throws, or try catch, otherwise it is also a compilation exception.

custom exception

basic concept

When some "errors" occur in the program, but the error information is not described and processed in Throwablethe subclass , at this time, you can design your own exception class to describe the error information.

Steps for custom exceptions

  1. Definition class: custom exception class name (written by the programmer) inherits Exception or RuntimeException
  • If you inherit Exception, it is a compilation exception

  • If you inherit RuntimeException, it is a running exception (generally speaking, inherit RuntimeException)

Application examples of custom exceptions

When we receive the age of the Person object, the range is required to be between 18-120, otherwise a custom exception (required to inherit RuntimeException) is thrown and a prompt message is given.

package com.hspedu.customexception_;

public class CustomException {
    
    
    // 方法声明处,throws 异常
    public static void main(String[] args) /*throws AgeException*/ {
    
    

        int age = 180;
        //要求范围在 18 – 120 之间,否则抛出一个自定义异常
        if(!(age >= 18 && age <= 120)) {
    
    
            //这里我们可以通过构造器,设置信息
            // 在方法体中,这里 throw 对象
            throw new AgeException("年龄需要在 18~120之间");
        }
        System.out.println("你的年龄范围正确.");
    }
}
// 自定义一个异常
// 1. 一般情况下,我们自定义异常是继承 RuntimeException
// 2. 即把自定义异常做成 运行时异常,好处是我们可以使用默认的处理机制,即自动向上throws异常,否则main中也得加throws。
class AgeException extends RuntimeException {
    
    
    public AgeException(String message) {
    
    //构造器
        super(message); // 调用父构造器,可以进入源码逐级查看。
    }
}

parent constructor:

    public Throwable(String message) {
    
    
        fillInStackTrace();
        detailMessage = message; // 传入 detailmessage
    }

The difference between throw and throws

practise

programming questions

Write an application that receives two arguments (integers) from the command line and calculates the division of two numbers.

Calculating the division of two numbers requires the use of the method cal(int n1, int n2)

Exception handling for incorrect data format (NumberFormatException), missing command line parameters (ArrayIndexOutOfBoundsException), and division by zero (ArithmeticException).

package com.hspedu.homework;

public class Homework01 {
    
    
    public static void main(String[] args) {
    
    
        /*
        编写应用程序EcmDef.java,接收命令行的两个参数(整数),计算两数相除。
        计算两个数相除,要求使用方法 cal(int n1, int n2)
        对数据格式不正确(NumberFormatException)、缺少命令行参数(ArrayIndexOutOfBoundsException)、除0 进行异常处理(ArithmeticException)。
         */

        try {
    
    
            //先验证输入的参数的个数是否正确 两个参数
            if(args.length != 2) {
    
    
                throw new ArrayIndexOutOfBoundsException("参数个数不对");
            }

            //先把接收到的参数,转成整数
            int n1 = Integer.parseInt(args[0]);
            int n2 = Integer.parseInt(args[1]);

            double res = cal(n1, n2);//该方法可能抛出ArithmeticException
            System.out.println("计算结果是=" + res);

        } catch (ArrayIndexOutOfBoundsException e) {
    
    
            System.out.println(e.getMessage());
        } catch (NumberFormatException e) {
    
    
            System.out.println("参数格式不正确,需要输出整数");
        } catch (ArithmeticException e) {
    
    
            System.out.println("出现了除0的异常");
        }


    }
    //编写cal方法,就是两个数的商
    public static double cal(int n1, int n2) {
    
    
        return n1 / n2;
    }
}

Guess you like

Origin blog.csdn.net/m0_52316372/article/details/130258860