Java Core Exception

Definition: Exceptions that occur during the running of the program

Architecture of all “problems” in Java

Throwable [can be thrown out]

Error 【Error】 Exception 【Exception】

RunTimeException [runtime exception]

//The difference between Error and Exception

Error is usually a relatively serious problem caused by hardware environment or system reasons

Exception refers to the exception that occurs during the running of the program and is relatively light

//Runtime exception and non-runtime exception

Non-running is an exception that requires a solution when compiling, otherwise the compilation will not pass

There is no need to provide a solution when compiling runtime exceptions Compilation can be passed directly, and the problem will be directly reflected at runtime

//Whether runtime exceptions or non-runtime exceptions occur at runtime, no exceptions will occur at compile time, only a solution will be required

Common runtime exceptions

Operator: ArithmeticException Arithmetic exception (0 cannot be a divisor in mathematics) In Java, if an integer is divided by 0, it will directly trigger the exception. Divide by 0.0 to get Infinity 0.0 / 0.0 to get NaN (not a number) NaN == any value is false including itself)

Array: NegativeArraySizeException Negative array size exception

(when defining an array)

ArrayIndexOutOfBoundsException Array index value exceeds subscript exception

(accessed beyond 0 – length – 1 )

String: NullPointerException Null pointer exception

(The default value of the reference data type is null, using it to access any property and calling any method will trigger the exception)

 //NullPointerException => null pointer exception
String str1 = null;
System.out.println(str1.length());

StringIndexOutOfBoundsException String index value out of bounds

NumberFormatException Number format exception (the wrapper class provides methods for converting from String to corresponding basic data types, such as Integer.parseInt() / Double.parseDouble() If there is illegal content in the provided string, the exception will be triggered directly)

 //NumberFormatException => number format exception
String str3 = "123a";
int price = Integer. parseInt(str3);
System.out.println(price + 3);

Type conversion: ClassCastException type casting exception (this exception is triggered when an object is to be converted to an unrelated type)

 //ClassCastException => type casting exception
Object stu = new Student();
Cat cc = (Cat)stu;

Collection IllegalArgumentException Illegal parameter exception (pass in a negative number when constructing)

IndexOutOfBoundsException Index value out of bounds exception

 //IndexOutOfBoundsException => index value out of bounds exception (collection)
List<Integer> list2 = new ArrayList<>();
Collections.addAll(list2,11,22,33);
System.out.println(list2.get(3));

IllegalStateException Illegal state exception (when using an iterator, next() can move the cursor down to point to the element, and then the element can be used to directly operate remove(), which will trigger the exception)

 //IllegalStateException => illegal state exception
List<Integer> list3 = new ArrayList<>();
Collections.addAll(list3,11,22,33);
Iterator<Integer> car = list3. iterator();
car. remove();

import java.util.*;
public class TestIllegalStateException{
public static void main(String[] args){
List<String> list = new ArrayList<>();
Collections.addAll(list,"Andy","Aaron","Jacky","Jay","Leon");
for(Iterator<String> car = list.iterator(); car.hasNext(); ){
String name = car. next();
if(name. startsWith("J")){
car. remove();
}
if(name. endsWith("y")){
car. remove();
}
}
System.out.println(list);//?
}
}

ConcurrentModificationException Concurrent modification exception (when using the iterator to traverse the collection, it is not allowed to add or delete the collection as a whole, otherwise the next next() of the iterator will trigger this exception)

Why handle exceptions:

1. If it is a non-runtime exception, if it is not handled, the compilation will not be completed

2. Once an unhandled exception occurs during the running of the program (thread), the virtual machine will directly interrupt the running

How to handle exceptions

1. throw back the superior throws

throws appears at the end of the method signature and is used to express that a specified type of exception occurs in this method. It will not be processed in the method and will be thrown back to the calling superior for processing.

2. Handle try and catch by yourself

try {

Statements that may throw exceptions

usually only one sentence

Unless the requirement dictates that the former has a problem, the latter will be skipped

}catch(exception type exception code to be obtained){

Handle the caught exception

0. Concealment and non-reporting

1. Brief arraignment

Exception code.getMessage();

2. Detailed review

Exception code.printStackTrace();

}finally{

The action to be performed eventually regardless of whether an exception occurs

Usually an operation that releases and closes resources

}

//A try can be followed by a parallel relationship or a catch branch larger than it, the former is not allowed to include the latter

//Before JDK7.0, if two kinds of exceptions are caught, the same operation must be done, and the catch must be written twice

JDK7.0 started to support multiple catch catch (type 1 | type 2 exception code) {. . . }

//Don’t write return statement in finally, otherwise the return in try catch is meaningless

How to actively create a scene where an exception occurs when there is no exception

throw is used in the body of the method when no exception occurs
Actively create scenarios where exceptions occur…

//The difference between throw and throws?
throws is used at the end of the method signature
Used to express the specified type of exception in this method
No processing is done in this method, and it is returned to the calling superior for processing

How to customize exceptions…
Develop a class by yourself and choose to inherit Exception / RuntimeException
Non-runtime exception Runtime exception

Use super(“Specify the description information of the exception”); in the first line of its construction method;

public class ExecThrow{
public static void main(String[] args){
showSeason(-15);
}
public static void showSeason(int month){
if(month <= 0 || month > 12){
throw new IllegalMonthException();
}
if(month <= 3){
System.out.println("Where is spring");
}else if(month <= 6){
System.out.println("Quiet summer");
}else if(month <= 9){
System.out.println("Autumn will not come back");
}else if(month <= 12){
System.out.println("About winter");
}
}
}
class IllegalMonthException extends RuntimeException{
public IllegalMonthException(){
super("The specified month is invalid~");
}
}

Plus01:
When a static variable in the class body is called by calling a method with an exception declaration
To complete the assignment, we cannot directly throws on the class signature
You can’t directly try catch in the class body. If you want to compile and pass
You must use the static initialization block to complete the try catch processing in the initialization block
*: If it is a non-static variable, you can use a non-static initialization block
Or use the constructor to complete the assignment

public class TestExceptionPlus01{
public static void main(String[] args){

}
}
class X{
static int a;
static {
try {
a = get();
}catch(Exception e){
e.printStackTrace();
}
}

public static int get() throws Exception{
int x = (int)(Math.random()*5) + 5;//5-9
if(x == 7 || x == 9){
throw new Exception("The generated number is very evil~");
}
return x;
}
}

Plus02:
When the method is overridden, if the parent method does not have any exception statement
So can the subclass method throw an exception when overriding it?
Yes, but can only throw out runtime exceptions
Because all methods in Java throw all runtime exceptions by default
Equivalent to the last of each method signature
There is a line of default throws RuntimeException…
Although it can, such behavior is pointless…

public class TestExceptionPlus02 {
public static void main(String[] args) throws RuntimeException{
C cc = new C();
cc.test();
}
}
class A extends Object{
public void test() throws RuntimeException{
System.out.println("test() method of parent class");
}
}
class C extends A{
@Override
public void test() throws IllegalArgumentException, ClassCastException, NullPointerException, ArithmeticException, NegativeArraySizeException{
System.out.println("subclass test() method");
}
}

Plus03:
When there are multiple lines of statements with exception statements in the program
We need to try to execute the latter regardless of whether the former executes abnormally
At this time, you must use the finally of try catch finally
Nested use of try catch…
We jokingly call this grammar: serial try~

public class TestExceptionPlus03{
public static void main(String[] args){
SLT no1 = new SLT();
SLT no2 = new SLT();
SLT no3 = new SLT();

try {
no1. close();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
no2. close();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
no3. close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
class SLT{
public void close() throws Exception{
int x = (int)(Math. random()*2);//0 or 1
if(x == 0){
throw new Exception("Unscrewed and unable to close the exception");
}
System.out.println("Closed the tap normally");
}
}

Plus04:
The try catch syntax structure added for exception handling is {}
This pair of braces can also control the scope of variables
If we need to use variables in the following program
You can’t define it in try{}, but put it in front of try{}
And assign the value with the default value. Only reassign the value in try{} without defining the variable

public class TestExceptionPlus04{
public static void main(String[] args){
int x = 0;
try {
x = get();
}catch(Exception e){
e.printStackTrace();
}

System.out.println(x);//?
}
public static int get() throws Exception{
int num = (int)(Math. random()*5);
if(num == 2 || num == 4){
throw new Exception("The generated number is unlucky");
}
return num;
}
}

Plus05:
In some scenarios, learn to use the mechanism of exception handling instead of traditional branching and judgment

public class TestExceptionPlus05{
public static void main(String[] args){
System.out.println(check("12a345"));
}
public static boolean check(String str){
try {
Integer. parseInt(str);
return true;
}catch(Exception e){
return false;
}

/*
for(int i = 0;i<str. length();i ++ ){
char x = str.charAt(i);
if(x < '0' || x > '9'){
return false;
}
}
return true;
*/
}
}

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Java skill treeHomepageOverview 107403 people are studying systematically