头图
This article participated in the Sifu technical essay , and you are welcome to join.

abnormal

An overview of exceptions


  • Exception means abnormal. In the Java language, it mainly refers to the errors generated by the program during the running phase.
  • Throwable (throwable, throwable)

    • The java.lang.Throwable class is the superclass for all errors or exceptions in Java programs
    • There are two main types

      • Error

        • Error mainly describes more serious errors
        • Critical bugs that cannot be fixed by programming
      • Exception

        • Exception mainly describes a relatively lightweight error
        • Can be solved by programming

The main classification of the Exception class

RuntimeException -> runtime exception, also called undetected exception class


  • The non-detected exception class refers to the exception that cannot be detected by the compiler during the b compilation phase.
  • main subclass

    • ArithmeticException -> Arithmetic exception class
    • ArrayIndexOutOfBoundsException (indirect subclass) -> array subscript exception class
    • NullPointerException -> null pointer exception
    • ClassCastException -> type cast exception
    • NumberFormatException (indirect subclass) -> number format exception
  • Notice

    • When an exception occurs during the execution of the program, if it is not handled manually, the Java virtual machine will use the default method to handle it. The default method is to print the exception name, the cause of the exception, and the location where the exception occurred, and terminate the program. The subsequent code cannot be accessed. implement

IOException and other exception classes -> other exception classes, also called unchecked exceptions

case

TestRuntimeException.java

 package demo1;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/*
 *         ArithmeticException -> 算数异常类
        ArrayIndexOutOfBoundsException(间接子类) -> 数组下标异常类
        NullPointerException -> 空指针异常
        ClassCastException -> 类型转换异常
        NumberFormatException(间接子类)-> 数字格式异常
 */

public class TestRuntimeException {
    public static void main(String[] args) {
        
        
        // 观察检测性异常
        // FileInputStream fis = new FileInputStream("c:/a.txt");
    
        // java.lang.ArithmeticException 算数异常
        int a = 10; 
        int b = 0;
        if (b != 0) {
            System.out.println(a/b);
        }

        // java.lang.ArrayIndexOutOfBoundsException 数组下标越界异常

        int[] arr = new int[3];
        int num = 3;
        if (num >= 0 && num < arr.length) {
            System.out.println(arr[num]);
        }
 

        // java.lang.NullPointerException

        String str = null; 
        if (str != null) {
            System.out.println(str.length());
        }

        // java.lang.ClassCastException

        Exception ex = new Exception(); 
        if (ex instanceof IOException) {
            IOException ie = (IOException) ex;
        }

        // java.lang.NumberFormatException

        String s = "12be"; 
        if (s.matches("\\d+")) {
            System.out.println(Integer.parseInt(s));
        }
        System.out.println("运行程序结束");

    }
}

exception handling

How to handle runtime exceptions


  • For the vast majority of runtime exceptions, conditional judgment can be used to avoid the occurrence of exceptions

exception catch


  • syntax format

     try{
          可能产生异常对象的语句块
      }catch(异常类型 引用名){
          针对当前异常类型对象的处理语句块
      }
      .... (可以写多个catch)
      finally{
          无论是否发生异常,都应该执行的语句块
      }
  • Precautions

    • When there are multiple catch branches in the captured structure, remember that the exception type of a small range is placed above the exception type of a large range
    • Lazy writing:
      catch(Exception e) {....}
  • Implementation process
 try {
        a;
        b;  // 可能产生异常的语句
        c;
    } catch (Exception e) {
        e;
    } finally {
        f;
    }
    
- 当没有产生异常的时候,程序的执行流程是:a b c f 
- 当产生异常时,程序的执行流程是: a b e f
  • case

    • TestExceptionCatch.java

       package demo2;
      import java.io.FileInputStream;
      import java.io.FileNotFoundException;
      import java.io.IOException;
      
      public class TestExceptionCatch {
      public static void main(String[] args) {
      
          // 声明引用指向本类的对象,用于读取文件中的内容
          FileInputStream fis = null;
          try {
              // 随时可能产生文件找不到y异常对象, new FileNotFoundException()
              fis = new FileInputStream("d:/a.txt");
          } catch (FileNotFoundException e) {
              // 打印异常的名称、异常原因、异常的位置等信息
              e.printStackTrace();
          }
          
          try {
              fis.close();
          } catch (IOException e) {
              
              e.printStackTrace();
          } catch (NullPointerException e) {
              // System.out.println("输出");
              e.printStackTrace();
          }
      }
      }
    • TestFinally.java

       package demo3;
      
      public class TestFinally {
      public static void main(String[] args) {
          int a = 10;
          int b = 0;
          
          try {
              System.out.println(a/b);
          } catch (Exception e) {
              e.printStackTrace();
              return ;
          } finally {
              System.out.println("无论是否发生异常都会执行");
          }
          System.out.println("程序结束");
      }
      }

      java.lang.ArithmeticException: / by zero
      will be executed regardless of whether an exception occurs
      at demo3.TestFinally.main(TestFinally.java:9)

exception thrown

  • basic concept

    • In some special occasions, when an exception is generated but cannot be handled directly/does not want to be handled, the exception can be transferred to the caller of the current method at this time, which is called exception throwing.
  • syntax format

    • return value type method name (parameter list) throws exception type {....}
  • The principle of method overriding

    • The method name is required to be the same, the parameter list to be the same, and the return value type to be the same. Since jdk1.5, it is allowed to return subclass types
    • Scope permissions cannot be smaller, they can be the same or larger
    • cannot throw a larger exception
    • Notice

      • The overridden method in the subclass can choose to throw the same exception as the parent class, a smaller exception, or no exception, but cannot throw a larger exception or a different exception
      • case
        A.java

         package demo4;
        
        import java.io.IOException;
        
        public class A {
            public void show() throws IOException{
                System.out.println("A");
            }
        }

        SubA.java

         package demo4;
        
        import java.io.IOException;
        import java.io.FileNotFoundException;
        import javax.print.PrintException;
        
        public class SubA extends A{
        
            @Override
            // public void show() throws IOException {
            // public void show() throws FileNotFoundException {
            // public void show() throws PrintException {
            // public void show() throws Exception {
            public void show() {
            }
        }
        Obviously can't throw a bigger exception

custom exception

  • Origin of custom exception

    • Although a large number of exception classes are provided in the official Java library, they are not enough to describe all exceptions in real life. When there is an exception that is not described by m in the official library, the programmer needs to customize the exception class to describe it, so that the exception information is more targeted and readable.
  • Custom exception process

    • The custom class inherits from the Exception class or a subclass of the Exception class
    • Provides two versions of the constructor, one is a no-parameter constructor, and the other is a constructor with strings as parameters
  • custom exception --> case 1

    • Person.java

       package demo5;
      
      public class Person {
      private String name;
      private int age;
      
      
      
      public Person() {
          super();
      }
      public Person(String name, int age) throws Exception {
          super();
          setName(name);
          setAge(age);
      }
      public String getName() {
          return name;
      }
      public void setName(String name) {
          this.name = name;
      }
      public int getAge() {
          return age;
      }
      public void setAge(int age) throws Exception {
          if(age > 0 && age < 150) {
              this.age = age;
          } else {
              // System.out.println("年龄不合理");
              // 手动产生一个异常对象并抛出
              // throw new Exception();
              throw new AgeException("年龄不合理!");
          }
          System.out.println("产生异常的效果");
      }
      @Override
      public String toString() {
          return "Person [name=" + name + ", age=" + age + "]";
      }
      
      
      }
    • AgeException.java

       package demo5;
      
      public class AgeException extends Exception {
      
      /**
       * 
       */
      private static final long serialVersionUID = 1L;
      
      // 自定义无参的构造方法
      public AgeException() {
          
      }
      
      // 自定义使用字符串作为参数的构造方法
      public AgeException(String msg) {
          super(msg);
      }
      }
    • TestPerson.java

       package demo5;
      
      public class TestPerson {
      public static void main(String[] args) {
      
          Person p = null;
          try {
              p = new Person("张三", -12);
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          System.out.println(p);
      }
      }

      demo5.AgeException: Unreasonable age!
      null
      at demo5.Person.setAge(Person.java:33)
      at demo5.Person.<init>(Person.java:15)
      at demo5.TestPerson.main(TestPerson.java:8)

  • Custom Exception --> Case 2

    • Student.java

       package demo6;
      
      public class Student {
      private String name;
      private int id;
      
      
      public Student() {
          super();
      }
      public Student(String name, int id) throws IDException {
          super();
          setName(name);
          setId(id);
      }
      public String getName() {
          return name;
      }
      public void setName(String name) {
          this.name = name;
      }
      public int getId() {
          return id;
      }
      public void setId(int id) throws IDException {
          if (id > 0) {
              this.id = id;
          } else {
              // System.out.println("学号不合理");
              throw new IDException("学号不合理");
          }
          System.out.println("结束");
      }
      @Override
      public String toString() {
          return "Student [name=" + name + ", id=" + id + "]";
      }
      
      
      }
    • IDException.java

       package demo6;
      
      public class IDException extends Exception {
      
      /**
       * 
       */
      private static final long serialVersionUID = 1L;
      
      public IDException() {
          
      }
      
      public IDException(String msg) {
          super(msg);
      }
      }
    • TestStudent.java

       package demo6;
      
      public class TestStudent {
      public static void main(String[] args) throws IDException {
          
          /*Student stu = null;
          try {
              stu = new Student("小王", -5);
          } catch (IDException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }*/ 
          
          Student stu = new Student("小王", -5);
          System.out.println(stu);
      }
      }

      Exception in thread "main" demo6.IDException: Student ID is unreasonable
      at demo6.Student.setId(Student.java:30)
      at demo6.Student.<init>(Student.java:14)
      at demo6.TestStudent.main(TestStudent.java:14)

One thing to note here, in the TestPerson of case 1, in the main function, we use the try....catch statement, the exception is handled internally, and the following statement will be printed. In the TestStudent of case 2, we will The exception is directly handed over to the main function for processing, that is, to the virtual machine for processing, so the following statement will not be executed

Throwing of exception object

  • throw new exception type()
  • E.g:

    • throw new Exception()
Finally, briefly introduce the difference between throws and throws

The difference between throws and throws

  • throws

    • Used after the method declaration, followed by the exception class name
    • Can be followed by multiple exception class names, separated by commas
    • Indicates that an exception is thrown, which is handled by the caller of the method
    • throws represents a possibility of exceptions, and these exceptions do not necessarily occur
  • throw

    • Used in the method body, followed by the exception object name
    • Only one exception object name can be thrown
    • Indicates that an exception is thrown, which is implemented by the statement in the method body
    • Throw is throwing an exception, and executing throw must throw some kind of exception

若尘
54 声望10 粉丝