Java exceptions and exception handling

abnormal

Exception concept:
In the Java language, an abnormal situation that occurs during program execution is called an "abnormal"

Abnormal events (abnormal conditions during runtime) that occur during the execution of Java programs can be divided
into two categories:
• Error: serious problems that cannot be solved by the Java virtual machine. Such as: JVM system internal errors, resource
exhaustion and other serious situations. Generally do not write targeted code for processing.
• Exception: Other general problems caused by programming errors or accidental external factors can be
handled with specific codes. For example:
accessing array subscript out of bounds
, trying to read non-existing files,
network connection interruption

For these exceptions, there are generally two solutions: one is to terminate the operation of the program when an exception is encountered.
• Another method is for programmers to consider exception detection, exception message prompts, and exception handling when writing programs.
• Catching exceptions is ideally at compile time, but some exceptions only occur at runtime. For example: the divisor is 0, the array subscript is out of bounds, etc.

Exception Handling Basic Syntax

try{ code that may cause an exception }catch(exception type reference name){ exception handling code }finally{ code must be executed}




Grammar analysis

try
detects unsafe code blocks (find exceptions)
If an exception occurs in any statement in the try block, the following code will not be executed, and the program will
jump to the exception handling code block, that is, the catch block. Therefore, don't put irrelevant code
in the try block at will, because execution may be interrupted at any time.

The catch
catches the caught exception of the type matching to ensure that the program can continue to run. The
catch statement must be followed by the try statement, which is called the catch exception, that is, the exception handling function.
Multiple catches can be written after a try to catch different types of exceptions respectively. Write them in order from the subclass to the parent class,
otherwise there will be a compilation error

Information about catching exceptions:
Like other objects, you can access member variables of an exception object or call its methods.
getMessage() Get the exception information and return the string
printStackTrace() Get the exception class name and exception information, as well as the location where the exception occurred in the program
. The return value is void.

finally
finally the content will always be executed, there can only be one finally statement
finally{ the logic that must be executed

throws

● throws, when defining a method, you can use the throws keyword declaration, which means that this method
does not handle exceptions, but will be handed over to the method caller for processing.
For example:
public void test throws exception 1, exception 2, exception 3 { } ● Any method can use the throws keyword to declare the exception type, including abstract methods. ● The subclass overrides the method in the parent class, and the method of the subclass cannot declare to throw an exception larger than the type of the parent class (for compile- time exceptions). ● The method using throws must handle the declared exception when calling, either use try-catch, or continue to use the throws statement





throw

The throw keyword is used to explicitly throw an exception, and when it is thrown, it is an instantiated
object of the exception class. • In exception handling, what the try statement needs to capture is an exception object, so the exception object
can also be thrown by itself.
Syntax: throw throw new Exception class construction method
such as: throw new RunTimeException();

the difference

● throw is used in the method body to throw an actual exception object. After using throw,
either use try catch to catch the exception, or use throws to declare the exception.
Throws is used at the method declaration to declare the possible exception types of the method. It can be
multiple exception types and is used to force these exceptions to be handled when calling the method.
Abstract methods can also use throws

custom exception

Custom exception class
● Basic syntax
public class exception class name extends Exception/RuntimeException{ public exception class name (String msg) { super(msg); } } ● Custom exception classes often do not write other methods, only overload the construction method that needs to be used ● Inherit Exception, after using throw in the method, it must be thrown in try-catch or throws in the method






Chapter 7 Collection

A variable-length container generated in place of an array (immutable in length)

The collection includes four interfaces: Collection, Map, list, set

Eight classes: Arraylist, Linklist, vector, hashset, treeset, Hashmap, treemap, hashtable

Collection interface

Defines the methods for accessing a group of objects, and its sub-interfaces Set and List define the storage methods respectively.
● The data objects in the Set have no order and cannot be repeated.
● The data objects in the List have order and can be repeated.
Some common methods in the collection are defined in Collection:
boolean add(Object element); add element
boolean addAll(Collection c); add all elements in c boolean
remove(Object element); delete element boolean removeAll (Collection c); delete the intersecting element
when the specified collection does not contain void clear(); empty collection int size(); return collection length boolean isEmpty(); Determine whether it is empty boolean contains(Object element); whether it contains boolean containsAll(Collection c); whether it contains all the elements in c boolean retainAll(Collection c); find the intersection, if the collection data changes, return true, and if it does not change, return false







List inherits the Collection interface, and has three implementation classes
- ArrayList
, and the data is stored in an array.
-LinkedList
linked list
-Vector
array list, add synchronization lock, thread safe

  • ArrayList implements a variable-length array and allocates continuous space in memory. The efficiency of traversing elements and random access elements is relatively high
  • LinkedList uses linked list storage. It is more efficient when inserting and deleting elements

Common methods of ArrayList
add(int index, E element) Add element data to the specified position
get(int index) Get the element at the specified position indexOf(Object o ) Return the position where element o first appears
in the collection Use) set(int index, E element) to replace the specified position element



The common method of LinkedList
add(int index,Object element) Add element data to the specified position
addFirst(Object element) Head insert
addLast(Object element) Tail insert
get(int index) Get
removeFirst() Head delete
removeLast() Tail delete
remove(int index) Delete specified
getFirst() Get head
getLast() Get tail

Set interface
● The Set interface inherits the Collection interface.
The elements stored in the Set are not repeated, but they are out of order. The elements in the Set have no index. ● The Set
interface has two implementation classes.
● HashSet
The elements in the HashSet class cannot be repeated, that is, call the equals method to compare with each other, and both return false.
The underlying data structure is hash table + linked list.
Hash table relies on hash value storage
● TreeSet
can sort the elements in the Set collection in a specified way. Stored objects must implement the Comparable interface.
The underlying data structure of TreeSet is a binary tree (red-black tree is a self-balancing binary tree)

Common methods of Mapa interface
V put(K key,V value) Add
V remove(Object key) Delete the entire key-value pair according to the key value
void clear()
boolean containsKey(Object key) Whether the key is contained boolean
containsValue(Object value) Whether the value is contained boolean
isEmpty()
int size()
V get(Object key) Find the key according to
the value Collection values() Return all the values
​​Set Set keySet() Take out all the keys and return a non-repeating set

Map interface
● HashMap
The key values ​​of elements in HashMap cannot be repeated, and the arrangement order is not fixed, and a
null key can be stored.
● TreeMap
All the elements in the TreeMap maintain a fixed order. If you need to get an ordered
Map, you should use the TreeMap. The class where the key value belongs must implement the Comparable interface.
● HashTable
achieves synchronization.
Keys that cannot be stored as null

collections (tool class for collection processing)

1. What is Collections?

This class is composed only by static methods or returns collections. It contains polymorphic algorithms, "wrappers", that operate on collections, returning a new collection backed by the specified collection.

2. The main methods are as follows:

  • addAll(Collection<? super T> c, T… elements) Add all specified elements to the specified collection.
  • binarySearch(List<? extends Comparable<? super T>> list, T key) Searches the specified list for the specified object using the binary search algorithm.
  • copy(List<? super T> dest, List<? extends T> src) Copies all elements from one list to another.
  • emptyList() returns an empty list (immutable).
  • fill(List<? super T> list, T obj) replaces all elements of the specified list with the specified elements.
  • max(Collection<? extends T> coll) Returns the maximum element of the given collection according to the natural order of its elements.
  • min(Collection<? extends T> coll) Returns the smallest element of the given collection according to the natural order of its elements.
  • replaceAll(List list, T oldVal, T newVal) Replaces all occurrences of one specified value in the list with another.
  • reverse(List<?> list) Reverses the order of the elements in the specified list.
  • sort(List list, Comparator<? super T> c) Sorts the specified list according to the order induced by the specified comparator.
  • swap(List<?> list, int i, int j) swaps the elements at the specified positions in the specified list.

3. Code implementation.

package collectionsDemo;

import java.util.*;

public class CollectionsDemo {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<String> alist = new ArrayList<>();
        alist.add("a");
        alist.add("b");
        alist.add("c");
        Collections.addAll(alist,"d","e","f");//addAll(Collection<? super T> c, T... elements)将所有指定的元素添加到指定的集合。
        System.out.println(alist);
        ArrayList<Integer> alist1 = new ArrayList<>();
        alist1.add(1);
        alist1.add(3);
        alist1.add(2);
        alist1.add(7);
        alist1.add(4);
        alist1.add(2);
//        Collections.sort(alist1);
//        Collections.sort(alist1, new Comparator<Integer>() {//可自定义排序
//            @Override
//            public int compare(Integer o1, Integer o2) {
    
    
//                return o1-o2;
//            }
//        });
        Collections.sort(alist1,((o1, o2) -> {
    
    return o2-o1;}));
        System.out.println(alist1);
        System.out.println(Collections.binarySearch(alist1,1));//binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
        // 使用二叉搜索算法搜索指定对象的指定列表。
        Collections.swap(alist1,0,2);//交换指定列表中指定位置的元素
        System.out.println(alist1);

        ArrayList<Integer> alist2 = new ArrayList<>();
        alist2.add(0);
        alist2.add(0);
        alist2.add(0);
        alist2.add(0);
        alist2.add(0);
        alist2.add(0);
        alist2.add(0);
        alist2.add(0);
        alist2.add(0);
        Collections.copy(alist2,alist1);//copy(List<? super T> dest, List<? extends T> src)
        // 将所有元素从一个列表复制到另一个列表中。
        System.out.println(alist2);

        System.out.println(Collections.max(alist1));
        System.out.println(Collections.min(alist1));

        Collections.replaceAll(alist2,0,1);//将旧集合中的某一元素替换为新元素
        System.out.println(alist2);

        Collections.reverse(alist2);//翻转集合中元素
        System.out.println(alist2);

        List<Integer> alist3 = new ArrayList<>();
        alist3=Collections.emptyList();//返回一个不能更改的集合;

        System.out.println(alist3);
    }
}

4. Running results

[a, b, c, d, e, f]
[7, 4, 3, 2, 2, 1]
-1
[3, 4, 7, 2, 2, 1]
[3, 4, 7, 2, 2, 1, 0, 0, 0]
7
1
[3, 4, 7, 2, 2, 1, 1, 1, 1]
[1, 1, 1, 1, 2, 2, 7, 4, 3]
[]

Guess you like

Origin blog.csdn.net/weixin_52340450/article/details/125754170