Summary of abnormal use

The concept of abnormality

  • An exception is a mechanism by which a program notifies the caller of an error at run time.

  • The runtime refers to the errors that occur during the process of compiling the class file and executing it by the JVM. There are many kinds of exceptions. Different kinds of exceptions have different meanings and different handling methods.

Here's a chestnut:

public class Test {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        System.out.println(arr[4]);
    }
}


//results of enforcement
Exception in thread "main" 
java.lang.ArrayIndexOutOfBoundsException: 4
	at Test.main(Test.java:4)

Basic usage of exceptions

  • Capture exception
    • Basic grammar
try{ 
 Statements with potential exceptions; 
}catch (exception type exception object){
} finally {
 Abnormal exit
}
try blocks of code contain code that may have exceptions.
The catch code block contains the handling behavior after an exception.
The code in the finally code block is used to handle the aftermath work and will be executed at the end.
catch finally add or not according to the situation
  1. If an exception occurs in try, the program in the try code block will not continue to execute, but will be handed over to the code in catch for execution, and will continue to execute after the completion of catch execution.
public class Test {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        try {
            System.out.println("before");
            System.out.println(arr[4]);
            System.out.println("after");
        } catch (ArrayIndexOutOfBoundsException e) {
           //Call stack for printing exceptions
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }
}

//results of enforcement
before
java.lang.ArrayIndexOutOfBoundsException: 4
after try catch
  1. catch can only handle exceptions of the corresponding type
public class Test {
    public static void main(String[] args) {
        int[] arr = null;
        try {
            System.out.println("before");
            System.out.println(arr[4]);
            System.out.println("after");
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }
}
//results of enforcement
//Because it is a null pointer exception, the catch catches an exception type mismatch, which is thrown by the jvm and interrupted by the program.
before
Exception in thread "main" java.lang.NullPointerException
	at Test.main(Test.java:6)

  1. There can be more than one catch. `
public class Test {
   public static void main(String[] args) {
       int[] arr = null;
       try {
           System.out.println("before");
           System.out.println(arr[4]);
           System.out.println("after");
       } catch (ArrayIndexOutOfBoundsException e) {
           e.printStackTrace();
       } catch (NullPointerException e) {
           e.printStackTrace();
       }
       System.out.println("after try catch");
   }
}

//results of enforcement
before
java.lang.NullPointerException
after try catch

You can also write as follows:

catch (ArrayIndexOutOfBoundsException | NullPointerException e) { 
 ... 
} 
  1. You can also use a catch to catch all exceptions
public class Test {
    public static void main(String[] args) {
        int[] arr = null;
        try {
            System.out.println("before");
            System.out.println(arr[4]);
            System.out.println("after");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }
}

//Execution results
before
after try catch
java.lang.NullPointerException
	at Test.main(Test.java:6)

 The Exception class is the parent of all Exception classes, so you can use this type to represent the catch
 All exceptions.
Note: when a catch is used for type matching, it does not only match the same type of exception objects. 
It also catches subclass objects of the target exception type.
Like the code just now, NullPointerException and ArrayIndexOutOfBoundsException 
Are subclasses of Exception, so they can be caught.
  1. finally indicates the final rehabilitation work, such as releasing resources.
    No matter whether there is an exception or not, the code in finally will execute to. To ensure that it will eventually execute to the close method of Scanner.
public class Test {
    public static void main(String[] args) {
        int[] arr = null;
        try {
            System.out.println("before");
            System.out.println(arr[4]);
            System.out.println("after");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("fianlly code");
        }
        System.out.println("after try catch");
    }
}
//results of enforcement
java.lang.NullPointerException
before
	at Test.main(Test.java:6)
fianlly code
after try catch
  1. Use try to recycle resources.
 try (Scanner sc = new Scanner(System.in)) {
            int num = sc.nextInt();
            System.out.println("num = " + num);
        } catch (Exception e) {
            e.printStackTrace();
        }
  • Throw exception
    In addition to java's built-in classes throwing some exceptions, we can also throw an exception manually. Some descriptive languages can be formulated in the construction of abnormal objects.
public class Test {
    public static void main(String[] args) {
        invide(4,0);
    }
    public static int invide(int x, int y) {
        if (y == 0) {
            throw new ArithmeticException("Divisor is zero.");
        }
        return x / y;
    }
}

//results of enforcement
Exception in thread "main" java.lang.ArithmeticException: Divisor is zero.
	at Test.invide(Test.java:9)
	at Test.main(Test.java:5)

  • Exception description
    We can use the throws keyword to explicitly mark the exceptions that may be thrown at the location of the method definition, so as to remind the caller to pay attention to catching these exceptions.
 public static int invide(int x, int y) throws ArithmeticException {
        if (y == 0) {
            throw new ArithmeticException("Divisor is zero.");
        }
        return x / y;
    }
  • finally notes
    The time to finally execute is before the method returns (if there is a return in try or catch, it will execute finally before the return). However, if there is a return statement in finally, the return in finally will be executed, so that the original return in try will not be executed.
public static void main(String[] args) {
   System.out.println(func()); 
} 
public static int func() { 
  try { 
    return 10; 
  } finally { 
    return 20; 
  } 
} 

// results of enforcement
20 

Custom exception class
Declare a custom exception class
Inherit custom class from Exception
Write two constructors, one empty and one with parameters

public class NewException extends Exception{
    public NewException(String s) {//s according to your own needs
            super(s);
    }
}
public class Test {
    private static String userName = "admin";
    private static String password = "123456";

    static class UserError extends Exception {
        public UserError(String message) {
            super(message);
        }
    }

    static class PasswordError extends Exception {
        public PasswordError(String message) {
            super(message);
        }
    }

    public static void main(String[] args) {
        try {
            login("in", "123456");
        } catch (UserError userError) {
            userError.printStackTrace();
        } catch (PasswordError passwordError) {
            passwordError.printStackTrace();
        }
    }
    public static void login(String userName, String password) throws UserError,
            PasswordError {
        if (!Test.userName.equals(userName)) {
            throw new UserError("User name error");
        }
        if (!Test.password.equals(password)) {
            throw new PasswordError("Password error");
        }
        System.out.println("Landing successfully");
    }
}

//results of enforcement
Test$UserError: User name error
	at Test.login(Test.java:29)
	at Test.main(Test.java:19)

Keywords: Java jvm

Added by kwilder on Sun, 27 Oct 2019 06:39:57 +0200