Java learning -- day10_ Introduction to packaging classes, enumerations and exceptions

Java learning - day10_ Introduction to packaging classes, enumerations and exceptions

Packaging

Packaging class is a layer of packaging based on basic data types. A pair is maintained inside each wrapper class
The attribute of the corresponding basic data type is used to store and manage the data of a basic data type.

Wrapper class is a reference data type. Using wrapper class, you can make the basic data type data have the characteristics of reference type
Sex. For example, it can be stored in a collection. At the same time, several special methods are added to the wrapper class

Basic data type and package type

Definition: a corresponding class formed by encapsulating data of simple data type

Basic data type 									Packaging type
   byte	 									  Byte
   short 									  Short
   int 										  Integer
   long                                       Long
   float                                      Float
   double                                     Double
   char                                       Character
   boolean                                    Boolean

Packing and unpacking

Manual packing: the basic data type is used to complete the conversion to the corresponding packing type.

Function: for better storage

Mode 1:

This can be done through the construction method of each wrapper class. In the construction method of each wrapper class, there is a
An overloaded method with a corresponding basic data type as a parameter. At this point, the basic data classes that need to be packaged are directly
Type, which can be written into the parameters of the construction method to complete packing.

Byte n1 = new Byte((byte)1);
Short n2 = new Short((short)2);     
Integer n three = new Integer(3);
Long n4 = new Long(4L);
Float n5 = new Float(3.14f);
Double n6 = new Double(3.14);
Character n7 = new Character('a');
Boolean n8 = new Boolean(false);
[recommended] method 2:

Boxing can be done through the static method valueOf() of the wrapper class. In each wrapper class, there is a static method valueOf whose parameters are the parameters of the basic data type corresponding to the wrapper type. Directly write the data of the basic data type to be packaged into the parameters of this method to complete the packing of the basic data type data.

Byte n1 = Byte.valueOf((byte)1);
Short n2 = Short.valueOf((short)2);
Integer n3 = Integer.valueOf(3);
Long n4 = Long.valueOf(4);
Float n5 = Float.valueOf(3.14f);
Double n6 = Double.valueOf(3.14);
Character n7 = Character.valueOf('a');
Boolean n8 = Boolean.valueOf(true);

Manual unpacking: the conversion from the package type to the corresponding basic data type is completed.

Function: to facilitate operation

Method: the xxxValue of each wrapper class object can be implemented. xxx here is the basic number to be transformed
Data type. For example, if you need to convert to int type, you can call intValue directly.

Byte i1 = Byte.valueOf((byte) 100);
byte n1 = i1.byteValue();
 
Short i2 = Short.valueOf((short) 100);
short n2 = i2.shortValue();
 
Integer i3 = Integer.valueOf(100);
int n3 = i3.intValue();
 
Long i4 = Long.valueOf(100);
long n4 = i4.longValue();
 
Float i5 = Float.valueOf(3.14f);
float n5 = i5.floatValue();
 
Double i6 = Double.valueOf(3.14);
double n6 = i6.doubleValue();
Character i7 = Character.valueOf('a');
char n7 = i7.charValue();
 
Boolean i8 = Boolean.valueOf(true); 
boolean n8 = i8.booleanValue();

ps: some packaging objects, except the data that can be unpacked into the corresponding basic data type. It can also be packaged
To convert the data into other basic data types. For example, Integer, in addition to intValue, also has
byteValue and other methods. In fact, it is to forcibly convert the int data wrapped in the wrapper class into byte type and return carry forward
Fruit. When using, find the method you need to transform.

Automatic packing and unpacking

Concept: the so-called automatic packing and unpacking means that the above methods are no longer used when packing and unpacking
Method to complete the operation of packing and unpacking. At jdk1 After 5, packing and unpacking can be completed automatically! Only one assignment is required
Statement!

Method: without any special syntax, you can directly assign values.

// Automatic packing: conversion from a basic data type to the corresponding packing type. Only one assignment statement is required.
Integer i1 = 10;
// Automatic unpacking: conversion from a package type to the corresponding basic data type. Only one assignment statement is required.
int a = i1;

ps: now that you have automatic packing and unpacking, why do you have to master manual packing and unpacking. Because there are
In some cases, automatic packing and unpacking cannot be used.

ex: if there are two parameter types in an overloaded method of a class, one is the basic data type and the other is the
Corresponding packaging type. At this time, automatic packing and unpacking will not be available. The correspondence must be completed through manual packing and unpacking
Method call

//Logic that automatic packing and unpacking cannot be completed:
public class Program2 {
    public static void main(String[] args) {
        // At this point, 10 will match the parameter of type int first
        show(10);
        show(Integer.valueOf(10));
    }
    public static void show(int a) {
        System.out.println(a);
    }
    public static void show(Integer a) {
        System.out.println(a);
    }
}
Sharing principle

Concept: it is a basic principle of programming. When we need to frequently use some metadata in the program, this
We can prepare these metadata in advance and take them directly for use when necessary. Use complete
After that, it will not be destroyed for further use.

Sharing element in packaging class: store the packaging class objects corresponding to common basic data types in advance. When used here
Some wrapper objects corresponding to basic data types can be used directly without instantiating new objects
Yes.

Example: in the Integer class, the wrapper class object corresponding to the number in the range [- 128, 127] is pre stored in a
Integer. In the cache array, whenever we use numbers in this range, we can get them directly from this array
Get the element. If a number outside this range is used, instantiate a new wrapper class object. So,
There is no need to frequently open up and destroy space, which saves CPU resources.

Integer i1 = Integer.valueOf(10);
Integer i2 = Integer.valueOf(10);
System.out.println(i1 == i2);      
// At this time, since 10 is in the cache range, you can get the wrapper class object directly from the array. true. 
 
Integer i3 = Integer.valueOf(200);
Integer i4 = Integer.valueOf(200);
System.out.println(i3 == i4);      
// At this point, since 200 is not in the cache range, this method will return a new wrapper class object. false. 

String and basic data type conversion

Basic data type transformation string type

Concept: the basic data type is converted into a string. The desired result is the style of converting this value into a string. his
In fact, it is to add double quotation marks directly to this value.

**Method 1: * * can be completed by using string splicing operator. When either side of the plus sign is a string, it will
Automatically convert the other party into a string to complete string splicing. So when you need to put a number of basic data types
When converting data into a string, you only need to splice an empty string at the other end.

int a = 10;
String str = a + "";

[recommended] method 2: use the static method valueOf string to complete.

String str = String.valueOf(10);

Method 3: with the help of the instance method toString method of the wrapper class.

String str = Integer.valueOf(10).toString();

Method 4: with the help of the static method toString method of the wrapper class.

String str = Integer.toString(10);
String type transformation basic data type

Concept: converting a string type to a basic data type is actually parsing the contents of the string and transforming it into a corresponding base
Representation of this data type.

Note 1: there must be no problem converting basic data type to string, but changing from string type to basic data type
There may be problems when. The content in the string may not be converted to the basic data type you want to convert. as
If the conversion fails, a NumberFormatException exception will appear.

Note 2: for integers, if other non numeric characters appear in the string, the conversion to integer will be lost
Failure, even the decimal point, can not be turned. There is no conversion to floating point numbers and then to integers.

Method 1: use the static valueOf method of wrapper class (directly convert to basic data type)

Integer num = Integer.valueOf("123");		//Convert to package type

Method 2: use the static method parseXXX method of the wrapper class. XXX here is the basic data type to be converted.

int number = Integer.parseInt("123");		//Convert directly to basic data type

ps: string type. It is not similar to the above method. It can be directly converted to character type. If a string is to be converted to
Character, you need to use an instance method of the string, the charAt() method. Use this method to get the
The character that specifies the subscript.

Realize the conversion between hexadecimals
  • Convert decimal to other base
    • Integer.toHexString() to hex
    • Integer. Toctalstring() to octal
    • Integer.toBinaryString() to binary
String hex = Integer.toHexString(1234);
System.out.println(hex);
  • Convert other base to decimal
//First parameter: data - stored as a string
//Second parameter: hexadecimal - hexadecimal before conversion
Integer.parseInt(data,Base system)
int i2 = Integer.parseInt("10100011",2);
System.out.println(i2);

Common class

In the development process, many functions are commonly used by everyone. The system improves many functions in order to use methods and improve development efficiency
Pre encapsulation becomes a common class

Concept: it is a mathematical class. This class encapsulates many methods for mathematical calculation. They are static methods and square methods
Called.

Common static constants
attribute 							describe 									value
 PI                          PI                      3.14159265358979323846
 E                          Natural logarithm                      2.7182818284590452354 

common method

method                         parameter                                     describe
abs                     int/long/float/double                Calculate the absolute value of a number
max  (int, int)/(long, long)/(float, float)/(double, double) Calculate the maximum of two numbers
min  (int, int)/(long, long)/(float, float)/(double, double) Calculate the minimum of two numbers
round                   float/double                        Calculate the rounding of a number
floor                   float/double                        Calculates the downward rounding of a number
ceil                    float/double                        Calculate the upward rounding of a number
pow                    (double, double)                     Calculates the specified power of a number
sqrt                        double                           Calculate the square root of a number
random                         -                 Get a [0,1) Floating point random number in range
public class MathUsage {
    public static void main(String[] args) {
        System.out.println(Math.abs(-3));       // Calculate the absolute value of a number
        System.out.println(Math.max(10, 20));   // Calculate the maximum of two numbers
        System.out.println(Math.min(10, 20));   // Calculate the minimum of two numbers
 
        System.out.println(Math.round(3.14));   // rounding
        // Round down to find the first integer smaller than this number
        System.out.println(Math.floor(3.14)); 
        // Round up to find the first integer greater than this number
        System.out.println(Math.ceil(3.14));   
        System.out.println(Math.pow(2, 3));     // Calculate the third power of 2
        System.out.println(Math.sqrt(4));       // Calculate 4 square
        // Demand: calculate the cube root of 27
        System.out.println(Math.pow(27, 1/3.0));
        
        System.out.println(Math.random());                  // [0, 1)
        // [0, 100) integer random number
        System.out.println((int)(Math.random() * 100));     
    }
}
Common Random [meeting]

Concept: it is a class specially responsible for generating Random numbers. In Java, the Random class is in Java Util package. A pilot pack is required before use.

common method

method 			parameter 								     describe
Random		  nothing 				By taking the system time as the seed of random number, an example is instantiated Random object
Random        int 				 Instantiate a random number through a specified random number seed Random object
nextInt       int   			Generate a [0, bounds) Integer random number in range
nextInt       nothing 				Generate a int Random number in range
nextFloat 	  nothing 				Generate a [0, 1) Within range float Random number of type
nextDouble    nothing 				Generate a [0, 1) Range double Random number of type
nextBoolean   nothing					 Randomly generate a boolean numerical value
public class RandomUsage {
    public static void main(String[] args) {
        // 1. Instantiate a Random object
        Random random = new Random(1);
        // 2. Generate random numbers
        for (int i = 0; i < 20; i++) {
            // Generate random numbers in the range of [0, 50)
            System.out.print(random.nextInt(50) + ", ");
        }
    }
}
Common classes BigInteger, BigDecimal

BigInteger: represents an integer number, unlimited range

BigDecimal: represents a floating-point number, unlimited range and digits after the decimal point

common method

method 						parameter 								describe
 Construction method 				String 					Instantiate an object through a numeric string
add              BigInteger/BigDecimal                      plus
subtract         BigInteger/BigDecimal                      reduce
multipy 	     BigInteger/BigDecimal                      ride
divide           BigInteger/BigDecimal                      except
divideAndRemainder     igInteger/BigDecimal			except, Retain quotient and remainder save quotient to result number
													Bit 0 of the group saves the remainder to the end of the result array
													1st place
xxxValue                   - 			   The result of converting to the specified basic data type (may overflow)
public class BigIntegerAndBigDecimal {
    public static void main(String[] args) {
        // 1. BigInteger class
        BigInteger n1 = new 
		BigInteger("12347328461827364812736481726348712643872");
        BigInteger n2 = new 
		BigInteger("3824237487123847198734987231762386");
 
        // 2. Four operations
        BigInteger add = n1.add(n2);                    // addition
        System.out.println(add);
        igInteger subtract = n1.subtract(n2);          // subtraction
        System.out.println(subtract);
 
        BigInteger multiply = n1.multiply(n2);          // multiplication
        System.out.println(multiply);
 
        BigInteger divide = n1.divide(n2);              // division
        System.out.println(divide);
 
        // Divide n2 by n1 and retain quotient and remainder
        // Save quotient to bit 0 of result array
        // Save the remainder to bit 1 of the result array
        BigInteger[] bigIntegers = n1.divideAndRemainder(n2);
        System.out.println(bigIntegers[0]);     // export merchant
        System.out.println(bigIntegers[1]);     // Output remainder
 
        long ret = bigIntegers[0].longValue();
    }
}
Common class Date

Concept: it is a class used to describe time and date. In * * Java Util * * in package!!!

ps: compare Date and Data classes

Date:Date class
Data:Data class,It contains binary data

ps: compare Java util. Date and Java sql. Date package

java.util.date   Corresponding to java Date type,Including month, day, hour, minute and second
java.sql.date    This corresponds to the date type of the database ,Only include mm / DD / yy
 
If data type conversion is required,from java.sql.date Turn into java.util.date Is automatic type conversion,The opposite is mandatory
 Type conversion

Common methods:

method   		 parameter 								describe
Date 		   - 					item base  Date Object to describe the current time of the system.
Date 		 long 			Instantiate a with a specified timestamp Date Object describing the specified time.
getTime        - 	 Get the timestamp corresponding to a date, and the number of milliseconds calculated from 0:0:0 on January 1, 1970.
setTime      long 				Modify the time described by the time object by modifying the timestamp of a time.
equals 		 Date 							Judge whether the two times are the same
before 		 Date 					 Judge whether one time is before another
after		 Date 					 Determine whether one time is after another
public class DateUsage {
    public static void main(String[] args) {
        // 1. Instantiate a Date object
        Date date = new Date();
 
        // 2. Obtain the corresponding timestamp of a date (the number of milliseconds from 0:00 on January 1, 1970)
        long timestamp = date.getTime();
 
        // 3. Instantiate a Date object
        Date date1 = new Date(1586587414273L);
        System.out.println(date1);
 
        // 4. Modify the time described by this object by setting a timestamp
        date1.setTime(1586587414273L);
        System.out.println(date.equals(date1));     // Judge whether the two times are the same
        // Judge whether one time is before another
        System.out.println(date.before(date1));  
        // Determine whether one time is after another
        System.out.println(date.after(date1));      
    }
}
Common class SimpleDateFormat [will]

Concept:

  • Is a class used to format time. Using this class, there are generally two operations:
  • Converts a Date object into a time string in the specified format.
  • Converts a time string in the specified format into a Date object.
Placeholder description
y Indicates the year. Commonly used  	yyyy  Indicates long-term score.   yy  Indicates a short year.
M Indicates month. Commonly used   MM  Indicates that two digits are occupied. If the month is less than two digits, fill zero forward.
d Represents the day. Commonly used   dd  Indicates that two digits are occupied. If the date is less than two digits, fill zero forward.
H Indicates hour, 24-hour system. Commonly used  HH  Indicates that two digits are occupied. If the time is not enough for two digits, fill zero forward.
h Indicates hour, 12 hour system. Commonly used  hh  Indicates that two digits are occupied. If the time is not enough for two digits, fill zero forward.
m Indicates a score. Commonly used  mm  Indicates that two digits are occupied. If the score is less than two digits, fill zero forward.
s Indicates seconds. 	Commonly used  ss  Indicates that two digits are occupied. If the second is less than two digits, fill zero forward.
S Indicates milliseconds. Commonly used  SSS  Indicates that three bits are occupied. If the millisecond is less than three bits, fill zero forward.

common method

method 				      parameter 								describe
SimpleDateFormat      String 			    Instantiate an object through a specified time format.
format                 Date 			    Will one Date Object to a string in the specified format.
parse                 String          Parses a time string in a specified format into a Date Object.

ps: parse method
A compile time exception is thrown. When using, at present, directly use one click repair (alt + Enter), and use
Try catch can be surrounded.
Parses a string in the specified format. If the time format in the string, and object instantiation
When the given format is different, an exception will appear.

public class SimpleDateFormatUsage {
    public static void main(String[] args) {
        // format();
        // parse();
        System.out.println(getDeltaDays("2002-09-28", "2020-04-11"));
    }
 
    // Converts a time object into a string in the specified format
    private static void format() {
        // 1. Get the current time of the system
        Date now = new Date();
        // 2. Specify a time format, for example: 18:09:49, April 11, 2020
        String format = "yyyy year M month d day HH:mm:ss";
        // 3. Instantiate a SimpleDateFormat object through a time format
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        // 4. Convert to a string in the specified format
        String str = sdf.format(now);
        System.out.println(str);
    }
 
    // Converts a specified format string into a time object
    private static void parse() {
        // 1. Instantiate an object through a time format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 
HH:mm:ss");
        // 2. Parse a string in the specified format into a Date object
        try {
            Date date = sdf.parse("2019-09-27 22:18:05");
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
Common class Calendar [understand]

Concept: it is a class used to describe time and Date. More complete than Date. In the Date class, many methods have been
Abandoned. Replace with some methods in the Caleendar class.

public class CalendarUsage {
    public static void main(String[] args) {
        // 1. Calendar is an abstract class and cannot be instantiated directly
        Calendar calendar = Calendar.getInstance();
 
        // 2. Obtain the corresponding value through the specified field.
        //    In the Calendar class, several static constants have been encapsulated to represent different fields.
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.println(calendar.get(Calendar.MONTH));           // stay
Calendar In, the month starts at 0.
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
        System.out.println(calendar.get(Calendar.MINUTE));
        System.out.println(calendar.get(Calendar.SECOND));
 
        // 3. Set the corresponding value through the specified field
        calendar.set(Calendar.YEAR, 2022);
        calendar.set(Calendar.DAY_OF_MONTH, 29);
 
        // 4. Set month, year and day at the same time
        calendar.set(2021, Calendar.SEPTEMBER, 7);
        //    At the same time, set the month, day and time
        calendar.set(2022, Calendar.NOVEMBER, 12, 23, 59);
        //    At the same time, set the month, day, hour, minute and second
        calendar.set(2022, Calendar.NOVEMBER, 12, 23, 59, 59);
 
        // 5. Get date (Date object)
        Date date = calendar.getTime();
        // 6. Set date (Date object)
        calendar.setTime(new Date());
        // 7. Get timestamp
        long timestamp = calendar.getTimeInMillis();
        // 8. Set timestamp
        calendar.setTimeInMillis(timestamp);
 
        // 9. Judge whether one date is before another
        //    Similar methods include equals and after
        calendar.before(Calendar.getInstance());
 
        // 10. Add a date
        calendar.add(Calendar.MONTH, 3);
        calendar.add(Calendar.DAY_OF_MONTH, 21);
 
        System.out.println(calendar);
    }
}
System [understand]

Concept:

  • The System class contains some useful class fields and methods. It cannot be instantiated.
  • In the facilities provided by the System class, there are standard input, standard output and error output streams; Externally defined attributes and rings
    Access to environmental variables; Methods of loading files and libraries; There are also practical ways to quickly copy part of an array.

Common fields:

field 								Detailed description
err 						  "Standard error output stream.
in 								"Standard input stream.
out 							"Standard output stream.

Common methods:

common method 								Detailed description
currentTimeMillis() 			Returns the current time in milliseconds.
exit(int status) 				Terminate the currently running Java Virtual machine.
gc() 								  Run the garbage collector.
getProperties()						  Determines the current system properties.
nanoTime() 					Returns the current value of the most accurate available system timer, in nanoseconds.
setIn(InputStream in)				 Reassign the standard input stream.
setOut(PrintStream out) 			Reassign the standard output stream
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Properties;
import java.util.Scanner;
 
public class SystemDemo {
    public static void main(String[] args) {
        //Gets the current system time -- in milliseconds
        long time1 = System.currentTimeMillis();
        System.out.println("system time(millisecond):"+time1);
        //The current value of the most accurate available system timer
        long time2 = System.nanoTime();
        System.out.println("system time(Unit: nanosecond):"+time2);
        //Garbage collector
        // Calling the gc method implies that the Java virtual machine has made some effort to reclaim unused objects so that they can be used quickly
 Quickly reuse the memory currently occupied by these objects.
        // When control is returned from the method call, the virtual machine has done its best to recycle all discarded objects
 Space.
        // The function is the same as that of runtime getRuntime(). gc(); It's the same
 
        //Note: we'll use it a little when we talk about multithreading
        //System.gc();
        
        //Gets the current system properties.
     	Properties properties = System.getProperties();
        System.out.println(properties);
 
        //Get standard input stream
        InputStream in = System.in;
        //for example
        new Scanner(System.in);
        //Get standard output stream
        PrintStream out = System.out;
        //for example
        System.out.println();
    }
}

enumeration

Enumeration is also a user-defined data type and a reference data type. Enumerations are often used to describe some value ranges
Limited data.
For example:

  • Gender: there are only two values, which can be represented by enumeration
  • Month: there are only 12 values, which can be represented by enumeration
  • Week: there are only seven values, which can be represented by enumeration

Definition: enumeration type. The keyword enum is required. The name of the enumeration is an identifier, following the name of the big hump
Law.

public enum Gender {
    // List all possible values of this enumeration object
    // The elements in the enumeration are also identifiers and follow the big hump naming method
    Male, Female
}
public enum Month {
    Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
}
public enum Week {
    Mon, Tue, Wed, Thu, Fri, Sat, Sun
}

Use: enumeration is a custom data type that can declare variables. When using, directly use the enumeration type enum
The enumeration value is obtained in this form.

public class Test {
    public static void main(String[] args) {
        // Use of enumerations
        Gender gender1 = Gender.Male;
        Gender gender2 = Gender.Female;
 
        Month m1 = Month.Jan;
        Month m2 = Month.Nov;
 
        Week week1 = Week.Sat;
    }
}

Member definitions in enumeration [understand]

Enumeration can actually be regarded as a final subclass of the Object class. Cannot be inherited by other classes or enumerations.

public class EnumTest {
    public static void main(String[] args) {
        // 1. Get an enumeration object
        Gender gender = Gender.Male;
        // 1.1.  Proof method 1: enumerating objects, you can call methods in the Object class, indicating that these methods are from
Object Class.
        String str = gender.toString();
        // 1.2.  Proof method 2: it can be transformed upward to Object type.
        Object obj = gender;
    }
}
enum Gender {
    Male, Female
}
Attribute definitions in enumeration
public enum Gender {
    Male, Female;
    // 1. Define properties, methods and construction methods in enumeration Yes, it needs to be written below the enumeration element!
    //    If you need to define members in an enumeration, you need to add a semicolon after the last enumeration element.
    public String desc;
}

abnormal

Exception is a description of various abnormal conditions in the running process of the program.
If the program encounters an unhandled exception, the program cannot be compiled or run.
For example:

  • ArrayIndexOutOfBoundsException: the array subscript is out of bounds, which will cause the program to continue running.
  • NullPointerException: null pointer exception, which will make the program unable to continue execution.
  • ParseException: parsing date exception will cause the program to continue compiling.

Structure and classification of anomalies

In Java, throwable class is used to describe all abnormal situations. Throwable has two subclasses:
Exception and Error.

  • Error: describes the error information that occurs at the JVM virtual machine level. These errors cannot be handled.
  • Exception: describes the exception encountered by the program. Exceptions can be caught and handled.

Inheritance system of exceptions in Java:

  • Root class: Throwable
    • Error: error
    • Exception: exception
      • Runtime exception: RuntimeException

Classification of anomalies

  • According to the location of the exception

First: ordinary exceptions will cause the program to fail to compile. Such exceptions are called - compile time exceptions. (Non-
Runtime Exception: a non Runtime Exception, but it is often called a compilation exception because it occurs at compile time
Translation time exception.)

Second: Exception has a subclass - RuntimeException class, in which exceptions are automatically handled
Manage. This exception will not affect the compilation of the program, but if this exception is encountered during operation, it will lead to the execution of the program
Forced stop. Such exceptions are called - runtime exceptions.

  • Create the body of the exception class according to
    • First: the system is abnormal. The system is defined in advance and we can use it directly
    • Second: custom exceptions need to be defined by ourselves

How the anomaly works

public class Demo7 {
    public static void main(String[] args) {//4
        Math math = new Math();
        math.div(3,0);//3
    }
}
 
class  Math{
    public int div(int a,int b){//2
        return  a/b;//1  
    }
}

Principle description:

  • 1. Create an exception object (new ArithmeticException()) where the exception first occurs, because there is no exception here
    He has the ability to handle exceptions, so he will throw exceptions up to his method

  • 2. The div () method also has no ability to handle exceptions, so it will continue to throw up to the location where the method is called

  • 3. The location where the div() method is called does not have the ability to handle exceptions, so it will continue to throw it up to its method

  • 4. The main method also has no ability to handle exceptions, so it will continue to throw up and throw it to the JVM, which will call the exception object

    Print method to print the exception information to the console

Abnormal characteristics

When an exception occurs in the program, the exception information will be printed and the program will be interrupted. Therefore, when multiple exceptions occur at the same time, only
Can execute the first

public class Demo8 {
    public static void main(String[] args) {
        int[] arr = new int[] {4,5,6,6};
 
        //NullPointerException exception will be reported: null pointer exception
        arr = null;
 
        //An ArrayIndexOutOfBoundsException exception will be reported: array subscript out of bounds exception
        //In the current situation, this exception will not be executed. When the null pointer exception is executed, the program is interrupted
        System.out.println(arr[10]);
    }
}

Exception capture and handling

try-catch

If an exception is not handled, the program cannot be compiled or run.

  • grammar
try {
    // Write the code that may cause exceptions here
   // If there is an exception in the code here, all the code will not be executed from the place where the exception occurs to the end of the try code segment.
}
catch (Exception type identifier) {//Catch exception 
  /* If an exception occurs in the code in try, and the exception type and the exception type of catch can match, the logic here will be executed*/
}

Catch will listen to the code in the try. If there is no exception in the code in the try, catch will not execute and will execute directly
The code after the line If an exception occurs in the code in the try, catch will catch it immediately (effect: the code in the try will be caught immediately)
Break, execute catch directly)

public class Demo9 {
    public static void main(String[] args) {
        Math1 math = new Math1();
        try {//Possible exception codes
           
            math.div(3,0);
            //The code here can be executed only if there is no exception in the code in try
            System.out.println("try");
        }catch (ArithmeticException e){// The exception type of catch must be the same as the actual exception type in try
 The types of exceptions that occur are consistent
            //e.printStackTrace();   Get the location, reason and name of the exception
            System.out.println(e.getMessage());//reason
            System.out.println("catch");
              }
 
        System.out.println("go on");
    }
}
 
class  Math1{
    public int div(int a,int b){
        return  a/b;
    }
}

PS: the exception type caught in catch must be consistent with the actual exception type in try. Otherwise, no exception will be caught,
It will cause the actual exception in the try not to be caught and handled, and the compilation or operation of the program can still be terminated.

Multiple catch clauses
  • Usage scenario

If there are many types of exceptions in the try code segment, if you need to deal with these exceptions differently,
You can write multiple catch clauses.

In practical use:

  • If you want to handle different exceptions differently, you can use multiple catch es.
  • If you want to handle each exception in the same way, you can directly catch the parent exception.
//grammar
ry{
        Possible exception codes
}catch(Abnormal one  e){ //Catch exception e is the exception to catch
        Handling of current exception
}catch(Anomaly two  e){ //Catch exception e is the exception to catch
        Handling of current exception
}catch(Exception  e){ //Catch exception e is the exception to catch
        Handling of current exception
}
 
public class Demo10 {
    public static void main(String[] args) {
        Math2 math2 = new Math2();
        try {
            math2.div(3, 0);
        } catch (ArithmeticException e) {//Divisor zero exception
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {//Note: Exception exception must be placed in the last catch
            e.printStackTrace();
        }
    }
}
 
class Math2{
    public int div(int a,int b) {/*Second: there is no ability to handle exceptions here. Continue to throw them to the dispatcher
 Where to use this method*/
        int[] arr = null;
        System.out.println(arr[0]);
        return a/b;//First: an exception object with a divisor of zero (new ArithmeticException()) will be automatically generated first,
        //There is no ability to handle exceptions. The exception object will be thrown to its method
    }
}
        

ps:

Does the writing order of multiple catch es affect exception capture?

  • If there is no inheritance relationship between the exception types captured by multiple catch es, the order does not matter.
  • If there is an inheritance relationship between the exception types captured by multiple catch es, you must ensure that the parent exception is followed by the child exception
    Often in front.

A catch catches multiple exceptions [the code of this classification method is very confusing, so it is not recommended]

  • Usage scenario

    If multiple exceptions occur in the try, and some types of exceptions are handled in the same way. And with other types of processors
    The formula is different. At this point, you can use a catch catch to handle a variety of exceptions. When distinguishing multiple exceptions in a catch
    instanceof

public class Handle3 {
    public static void main(String[] args) {
        // Requirements:
        // NullPointerException ArrayIndexOutOfBoundsException is handled in the same way, and "array related exception" is output
        // Arithmeticexception numberformatexception are handled in the same way, and "format exception" is output
        try {
            nullPointerTest();      // NullPointerException
            outOfBoundsTest();      // ArrayIndexOutOfBoundsException
            arithmeticTest();       // ArithmeticException
            formatException();      // NumberFormatException
        }
        catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
            System.out.println("Array related exception");
                    if (e instanceof NullPointerException) {
                        System.out.println("NullPointerException");
                    }else if (e instanceof ArrayIndexOutOfBoundsException) 
{        
                         
 System.out.println("ArrayIndexOutOfBoundsException");
                    }
        }
        catch (ArithmeticException | NumberFormatException e) {
            System.out.println("Format exception");
        }
    }
 
    // NullPointerException
    private static void nullPointerTest() {
        int[] array = null;
        array[0] = 10;
    }
 
    // ArrayIndexOutOfBoundsException
    private static void outOfBoundsTest() {
        int[] array = new int[5];
        array[5] = 10;
    }
 
    // ArithmeticException
    private static void arithmeticTest() {
        int a = 10 / 0;
    }
 
    // NumberFormatException
    private static void formatException() {
        Integer i = Integer.valueOf("123a");
    }
}

ps: among multiple types of exceptions caught in a catch clause, exception types with inheritance relationship are not allowed

finally clause

Concept: finally appears at the end of the try catch clause. The content in the finally code segment will always be executed.

Syntax:

try{
    Possible exception codes
}catch(Exception  e){ //Catch exception e is the exception to catch
    Handling of current exception
}finally{
    Code that must be executed:It is mainly used for resource release:For example, close the database,Close flow,Close the lock, etc
}
characteristic:

Whether there are exceptions in the try code segment or not, and whether the exceptions in the try are not captured and processed, the code in finally
Always. Based on this feature, operations such as resource release and flow closure are often performed in finally

Scope of action

We found that after executing return in catch, the main method ends and finally can execute normally
Execute system. In catch After exit (0), the program exits and finally cannot be executed
Conclusion: as long as the current program is running, the finally code can be executed

public class Handle4 {
    public static void main(String[] args) {
        try {
            System.out.println(10 / 0);
        }
        catch (ArithmeticException e) {
            System.out.println("An arithmetic exception occurred");
            //return;// End the current function, and finally it can be executed
            System.exit(0);//Exit the program. finally, it can't be executed
        }
        finally {
            System.out.println("finally The content in the code snippet is executed");
        }
        System.out.println("end");
    }
}
Try finally statement [understand]

Syntax:

try{
  Get resources
}finally{
    Release resources
}

characteristic:
This structure has nothing to do with exceptions and is mainly used for resource management

public class Demo11 {
    public static void main(String[] args) {
        //Create lock object
                Lock lock;
        try {//Acquire lock
                      lock.lock();
        } finally {//Release lock
            lock.unlock();
        }
      System.out.println("go on");
    }
}

Two keywords

throw

An exception object has no meaning after being instantiated. It will not affect the compilation or operation of the program.
If you want an exception object to take effect (which can affect the compilation and operation of the program), you need to use the keyword throw
Exception thrown.

public class Handle5 {
    public static void main(String[] args) {
        int ret = calculate(10, 20);
        System.out.println(ret);
    }
 
    private static int calculate(int a, int b) {
        if (a > b) {
            return a - b;
            }
        // Otherwise, the argument is considered to have a logical error and an exception is thrown
        RuntimeException exception = new RuntimeException();
        // Let the current exception take effect so that it can terminate the program.
        // Moreover, an exception is thrown in a method. From this position, all backward code will not be executed.
        throw exception;
    }
}
            

throws

Used in the declaration part of the method, written after the parameter list and in front of the method body.
It is defined in the method to indicate what exceptions may be encountered at the end of the method process.
Defines the method of throws exception throwing type. In the current method, this exception can be handled by the caller instead of being handled.

public class Handle6 {
    public static void main(String[] args) {
        try {
            test2();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
 
    private static void test2() throws ParseException {
        test();
    }
 
    // throws ParseException:
    // 1. Tell the caller that there is an exception in this method. You should pay attention to it when using it.
    // 2. In this method, if a ParseException exception is encountered, it can not be handled. Who calls this method
 Method who handles it.
    private static void test() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // Parses a time string in the specified format into a Date object
        Date date = sdf.parse("2000-01-01");
        System.out.println(date);
    }
}
        

Custom exception

Why customize exceptions?
Exceptions are used to handle some major logical bugs. These logical bugs may cause the program to crash. this
You can use the exception mechanism to force the modification of this BUG.
In the system, many exception types are provided. However, no amount of exception types can meet all our needs
Demand. When the exception type we need is not provided by the system, we need to customize the exception.

How to customize exceptions?

Each exception provided by the system is a class. Therefore, a custom exception is actually a custom exception
Exception class.
If you want to customize a compile time Exception, you need to inherit from the Exception class.
Features: we have to complete all the work of handling exceptions manually
If you want to customize a runtime exception, you need to inherit from the RuntimeException class.
Features: we can ignore all work

User defined exception class. Theoretically, the class name can be defined arbitrarily. However, for the sake of standardization, it is generally
Exception As an end.
For example: ArrayIndexOutOfBoundsException, NullPointerException,
ArithmeticException...
Common exceptions:Order exception user exception negative exception

Using exceptions in overridden methods

Note:

  • The exception level declared in the method with the same name of the subclass should be < = that of the parent class
  • If a subclass method with the same name declares an exception, the parent class must declare an exception
  • The parent class throws an exception, and the child class can not throw an exception when overriding the method

Keywords: Java intellij-idea

Added by enemeth on Mon, 03 Jan 2022 21:19:59 +0200