Common API exceptions for Java basic learning

Posted by robinas on Tue, 01 Mar 2022 09:31:33 +0100

Java basic learning

Chapter 12 common API & exceptions

The reason for business trip has not been updated for a long time. I'm back to continue. I believe in perseverance, a little progress every day, and you can!!! come on.

preface

From graduation to work, there is no systematic sorting and recording of knowledge. Many knowledge know themselves, but they feel strange. It is useless to learn without thinking, so they decided to sort out the knowledge systematically.

Tip: the following is the main content of this article

1, Common API

1. Packaging

  1. Basic type packaging function
    a. The advantage of encapsulating basic data types into objects is that more functional methods can be defined in the object to manipulate the data
    b. One of the common operations: used for conversion between basic data type and string

  2. Packing class corresponding to basic type

    data typePackaging
    yteByte
    ortShort
    ntInteger
    ongLong
    loutFloat
    oubleDouble
    harCharacter
    ooleanBoolean
  3. Integer class
    a. Overview: wrap the value of the original type int in an object
    b. Construction method

    b. Code example

    public class IntegerDemo { 
    	public static void main(String[] args) { 
    		//public Integer(int value): creates an Integer object based on the int value (obsolete)
    		Integer i1 = new Integer(100); 
    		System.out.println(i1); 
    		//public Integer(String s): creates an Integer object based on the String value (obsolete) 				
    		Integer i2 = new Integer("100"); 
    		// Integer i2 = new Integer("abc"); //NumberFormatException 	 
    		System.out.println(i2); 
    		System.out.println("--------"); 
    		//public static Integer valueOf(int i): returns an Integer instance representing the specified int value 
    		Integer i3 = Integer.valueOf(100); 
    		System.out.println(i3); 
    		//public static Integer valueOf(String s): returns an Integer object that holds the specified value 
    		String Integer i4 = Integer.valueOf("100"); 	
    		System.out.println(i4); 
    	} 
    }
    
    
  4. Conversion between int and String types
    a. Convert int to String: add an empty String directly after the number; Through the static method valueOf() of String class
    b. Convert string to int: first convert the string number to Integer, and then call valueOf() method; Convert through Integer static method parseInt()

  5. Automatic packing and unpacking
    a. Automatic packing: convert the basic data type to the corresponding packing type
    b. Automatic unpacking: convert the packaging type to the corresponding basic data type
    c. Example code:

    Integer i = 100; // Automatic packing
    i += 200; // i = i + 200; i + 200 automatic unpacking; i = i + 200;  Automatic packing
    

2. Time and date

  1. Date class
    a. Overview: Date represents a specific time, accurate to milliseconds
    b. Date class constructor

    c. Code example

    public class DateDemo01 { 
    	public static void main(String[] args) { 
    		//public Date(): allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds 
    		Date d1 = new Date(); 
    		System.out.println(d1); 
    		//public Date(long date): allocate a Date object and initialize it to represent the specified number of milliseconds from the standard base time
    		long date = 1000*60*60; 
    		Date d2 = new Date(date); 
    		System.out.println(d2); 
    	}
    }
    
  2. Common methods of Date class
    a. Common methods

    b. Sample code

    public class DateDemo02 { 
    	public static void main(String[] args) { 
    		//Create date object 
    		Date d = new Date(); 
    		//public long getTime(): gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present 
    		// System.out.println(d.getTime()); 
    		// System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "year"); 
    		//public void setTime(long time): set the time. The value given is milliseconds 
    		// long time = 1000*60*60; 
    		long time = System.currentTimeMillis(); 
    		d.setTime(time); 
    		System.out.println(d); 
    	} 
    }
    
  3. SimpleDateFormat class
    a. SimpleDateFormat class overview: SimpleDateFormat is a concrete class used to format and parse dates in a locale sensitive manner.
    b. SimpleDateFormat class constructor

    c. Common methods of simpledateformat class
    -public final String format(Date date): formats the date into a date / time string
    -public Date parse(String source): parses text from the beginning of a given string to generate a date
    d. Sample code

    public class SimpleDateFormatDemo { 
    	public static void main(String[] args) throws ParseException { 
    		//Format: from Date to String 
    		Date d = new Date(); 
    		// SimpleDateFormat sdf = new SimpleDateFormat(); 
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss"); 
    		String s = sdf.format(d); 
    		System.out.println(s); 
    		System.out.println("--------"); 
    		//From String to Date 
    		String ss = "2048-08-09 11:11:11"; 
    		//ParseException 
    		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    		Date dd = sdf2.parse(ss); 
    		System.out.println(dd); 
    	} 
    }
    
  4. Calendar Class
    a. Overview of Calendar Class: calendar provides some methods for the conversion between a specific moment and a group of calendar fields, and provides some methods for operating calendar fields; Calendar provides a class method getInstance, which is used to obtain generally useful objects of this type. This method returns a calendar object. Its calendar field has been initialized with the current date and time: calendar rightnow = calendar getInstance();
    b. Common methods of Calendar Class

    c. Sample code

public class CalendarDemo { 
	public static void main(String[] args) { 
		//Get calendar class object 
		Calendar c = Calendar.getInstance(); 
		//public int get(int field): returns the value of the given calendar field 
		int year = c.get(Calendar.YEAR); 
		int month = c.get(Calendar.MONTH) + 1; 
		int date = c.get(Calendar.DATE); 
		System.out.println(year + "year" + month + "month" + date + "day"); 
		//public abstract void add(int field, int amount): adds or subtracts the specified amount of time from the given calendar field according to the rules of the calendar 
		//Example: three years ago today 
		// c.add(Calendar.YEAR,-3); 
		// year = c.get(Calendar.YEAR); 
		// month = c.get(Calendar.MONTH) + 1; 
		// date = c.get(Calendar.DATE); 
		// System.out.println(year + "year" + month + "month" + date + "day"); 
		
		//Example: 10 days after 10 years 
		// c.add(Calendar.YEAR,10); 
		// c.add(Calendar.DATE,-10); 
		// year = c.get(Calendar.YEAR); 
		// month = c.get(Calendar.MONTH) + 1; 
		// date = c.get(Calendar.DATE); 
		// System.out.println(year + "year" + month + "month" + date + "day"); 
		
		//public final void set(int year,int month,int date): sets the month, year and day of the current calendar 
		c.set(2050,10,10); 
		year = c.get(Calendar.YEAR); 
		month = c.get(Calendar.MONTH) + 1; 
		date = c.get(Calendar.DATE); 
		System.out.println(year + "year" + month + "month" + date + "day"); 
	} 
}

2, Abnormal

1. Abnormal

  1. Exception overview
    In the Java language, abnormal conditions occurring in program execution are called "exceptions". (syntax and logic errors in the development process are not exceptions)

  2. Abnormal architecture

    a. Error: a serious problem that cannot be solved by the Java virtual machine. Such as: JVM system internal error, resource exhaustion and other serious situations. For example: StackOverflowError and OOM. Generally, targeted code is not written for processing.
    b. Exception: general problems caused by programming errors or accidental external factors can be handled with targeted code.

    (1) Runtime exception: an exception that the compiler does not require forced handling. Generally refers to the logic error in programming, which is an exception that programmers should actively avoid.
    (2) Compile time exception: an exception that the compiler requires to be handled. That is, the general exception caused by external factors when the program is running. The compiler requires that Java programs must catch or declare all compile time exceptions.

  3. Common anomalies

    import java.io.File;
    import java.io.FileInputStream;
    import java.util.Date;
    import java.util.Scanner;
    import org.junit.Test;
    
    /*
     * 1, java exception architecture
     * 
     * java.lang.Throwable
     * 		|----java.lang.Error:Generally, targeted code is not written for processing
     * 		|----java.lang.Exception:Exception handling can be performed
     * 			|----Compile time exception (checked)
     * 				|----IOEXception
     * 					|----FileNotFoundException
     * 				|----ClassNotFoundException
     * 			|----Runtime exception (unchecked)
     * 				|----NullPointerException
     * 				|----ArrayIndexOutOfBoundsException
     * 				|----ClassCaseException
     * 				|----NumberFormatException
     * 				|----InputMismatchException
     * 				|----ArithmaticException
     * 
     */
    public class ExceptionTest {
    
    	// ******************The following are compile time exceptions***************************
    	@Test
    	public void test7() {
    //		File file = new File("hello.txt");
    //		FileInputStream fis = new FileInputStream(file);
    //		
    //		int data = fis.read();
    //		while(data != -1){
    //			System.out.print((char)data);
    //			data = fis.read();
    //		}
    //		
    //		fis.close();
    	}
    
    	// ******************The following are runtime exceptions***************************
    	// ArithmeticException arithmetic exception
    	@Test
    	public void test6() {
    		int a = 10;
    		int b = 0;
    		System.out.println(a / b);
    	}
    
    	// Inputmismatch exception input mismatch exception
    	@Test
    	public void test5() {
    		Scanner scanner = new Scanner(System.in);
    		int score = scanner.nextInt();
    		System.out.println(score);
    
    		scanner.close();
    	}
    
    	// NumberFormatException number formatting exception
    	@Test
    	public void test4() {
    		String str = "123";
    		str = "abc";
    		int num = Integer.parseInt(str);
    	}
    
    	// ClassCaseException type conversion exception
    	@Test
    	public void test3() {
    		 Object obj = new Date();
    		 String str = (String)obj;
    	}
    
    	// ArrayIndexOutOfBoundsException array index out of bounds exception
    	@Test
    	public void test2() {
    		// int[] arr = new int[10];
    		// System.out.println(arr[10]);
    
    		// String str = "abc";
    		// System.out.println(str.charAt(3));
    	}
    
    	// Null pointerexception null pointer exception
    	@Test
    	public void test1() {
    		// int[] arr = null;
    		// System.out.println(arr[3]);
    
    		// String str = "abc";
    		// str = null;
    		// System.out.println(str.charAt(0));
    	}
    }
    
  4. Exception handling mechanism
    a. try-catch-finally

    try {// Select the scope of catching exceptions, and put the code with possible exceptions in the try statement block.
    	Possible exception codes; 
    } catch(Exception class name variable name) { // Handling exception objects can be accompanied by one or more catch statements to deal with different types of exception objects that may occur.
    	Exception handling code; 
    } finally {// Optional 
    	Code that must be executed
    }
    

    b. throws + exception type - if a method may produce some kind of exception, but it is not sure how to handle it, the method should explicitly declare that it throws exceptions, indicating that the method will not handle these exceptions, but the caller of the method is responsible for handling them. The exception type after throws can be the exception type generated in the method or its parent class.
    c. Note:
    (1) The exception type thrown by the method overridden by the subclass shall not be greater than the exception type thrown by the method overridden by the parent class;
    (2) If the overridden method in the parent class does not handle exceptions in the throw mode, the overridden method of the child class cannot use throws, which means that if there are exceptions in the overridden method of the child class, it must be handled in the try catch finally mode;
    (3) In the executed method a, several other methods are called successively, which are executed in a progressive relationship. We suggest that these methods be processed in the way of throws. For the executed method a, try catch finally can be considered.
    d. Throwable member method

  5. Manually throw exceptions - Java exception class objects can be automatically generated and thrown by the system when exceptions occur during program execution, or manually created and thrown as needed.
    a. Throw method: first generate exception class objects, and then implement the throw operation through throw statement (submit to Java runtime environment)
    b. The exception that can be thrown must be an instance of Throwable or its subclass
    c. The difference between throws and throw

  6. Custom exception

    Example:

    public class ScoreException extends Exception { 
    	public ScoreException() {} 
    	public ScoreException(String message) { 			
    		super(message); 
    	} 
    }
    
    // Teacher class
    public class Teacher { 
    	public void checkScore(int score) throws ScoreException { 
    	if(score<0 || score>100) { 
    		// throw new ScoreException(); 
    		throw new ScoreException("The score you gave is wrong. The score should be 0-100 between"); } else { 
    		System.out.println("Normal performance"); 
    		} 
    	} 
    }
    // Test class
    public class Demo { 
    	public static void main(String[] args) { 
    		Scanner sc = new Scanner(System.in); 		
    		System.out.println("Please enter a score:"); 
    		int score = sc.nextInt(); 
    		Teacher t = new Teacher(); 
    		try {
    			t.checkScore(score); 
    		} catch (ScoreException e) { 
    			e.printStackTrace(); 
    		} 
    	} 
    }
    
    

Add wx: 15338507382, remark "java foundation"
Get a full set of learning manual for Java development for free

Topics: Java