1. Abnormal
Basic understanding of exceptions:
1. An exception is a problem that may occur during the "compilation" or "execution" of the program.
2. Abnormality is a phenomenon that the program cannot achieve a complete execution process.
Reason for exception:
(1) Note: The following exception types are all inherited from RuntimeException or subclasses of RuntimeException. There are generally two reasons for RuntimeException: on the one hand, the programmer's business is not considered well, and on the other hand, the programming logic is not rigorous.
1. Array index out of bounds exception: ArrayIndexOutOfBoundsException
public class ExceptionDemo{ public static void main(String[] args){ //Array index out of bounds exception: ArraIndexOutOfBoundsException int[] arr = {1,2,3} System.out.println(arr[2]); System.out.println(arr[3]);//When the code executes this line, an array index out of bounds exception will occur } }
2. Null pointer exception: NullPointerException (There is no problem with direct output of a null pointer, but an error will be reported when calling the function of a variable with a null pointer)
public class ExceptionDemo{ public static void main(String[] args){ //Null pointer exception: NullPointerException String name = null;//Represents no pointer to any string System.out.println(name);At this point the output is fine System.out.println(name.length());//An error will be reported when calling length() } }
3. Type conversion exception: ClassCastException
public class ExceptionDemo{ public static void main(String[] args){ //Type conversion exception: ClassCastException Object o = 23; String s = (String) o;//A string variable cannot point to an integer variable } }
4. Abnormal math operation: ArithmeticException
public class ExceptionDemo{ public static void main(String[] args){ //Mathematical operation exception: ArithmeticException int c = 10 / 0; } }
5. Number conversion exception: NumberFromatException
public class ExceptionDemo{ public static void main(String[] args){ //Number conversion exception: NumberFormatException String number = 334aaas; Integer it = Integer.valueOf(number); System.out.println(it+1); } }
(2) Here is a compile-time exception:
Note: The function of exceptions at compile time is to worry that programmers will not think well when programming, and errors will burst out during the compilation stage. The purpose is to remind you not to make mistakes!
public calss Exception{ public static void main(String[] args){ String data = "2020-01-12 10:23:21"; //Create a simple date formatting class: SimpleDateFormat sdf = new SimpleDateFormat(pattern:"yyyy-MM-dd HH:mm:ss"); //Parse string time into date object Date d = sdf.parse(date);//Here, a red wavy line will pop up under parse, and the exception type is ParseException System.out.println(d); } }
At this point, you can use throws to throw an exception for processing. If you don't handle it, you can't pass it when compiling.
public calss Exception{ public static void main(String[] args) throws ParseException{ String data = "2020-01-12 10:23:21"; //Create a simple date formatting class: SimpleDateFormat sdf = new SimpleDateFormat(pattern:"yyyy-MM-dd HH:mm:ss"); //Parse string time into date object Date d = sdf.parse(date); System.out.println(d); } }
Exception classification:
Generally, the exceptions encountered in programming are divided into runtime exceptions (all RuntimeException and its subclasses) and compile-time exceptions (Exception and its direct subclasses).
Runtime exception: An exception inherited from RuntimeException or an exception inherited from a subclass of RuntimeException will not report an error during the compilation phase, but will only report an error during the runtime phase.
Compile-time exception: No inheritance: The exception of RuntimeException will report an error during the compilation phase.
Note: All exceptions inherit from Throwable, and Throwable inherits from Object.
2. Exception handling mechanism
The purpose of handling exceptions: to avoid exceptions in the program from affecting the running of the program, and at the same time handle possible exceptions to make the code more robust.
1. The default processing flow of exceptions (the default processing mechanism is not ideal)
1. By default, an exception object will be created at the code location where the exception occurs: for example, ArrayIndexOutOfBoundsException.
2. The exception will be thrown to the caller from the point where it appears in the method, and the caller will eventually throw it to the JVM.
3. After the virtual machine receives the exception object, it first outputs the exception stack information data directly on the console.
4. Terminate the current program directly from the currently executing exception point.
5. Subsequent codes are no longer executed.
2. Compile-time exception handling mechanism
(1) Three processing methods for compile-time exceptions
1. When an exception occurs, it is thrown directly to the caller, and the caller continues to throw it.
2. When an exception occurs, catch and process it yourself.
3. Combining the former two, if an exception occurs, it will be thrown directly to the caller, and the caller will catch and process it.
(2) Display of processing methods
1.throws: Used in methods, exceptions that occur inside the method can be thrown to the caller of the method for processing.
(Note: This method is not friendly. When an exception occurs, it will not be handled by itself. If the exception is finally thrown to the JVM, it will cause the program to die.)
2.try...catch...
This method is called monitoring and catching exceptions. It is used inside the method to directly capture and process the exceptions that occur inside the method.
Since the method of releasing the exception completes the exception handling independently, the program can continue to execute.
try-catch basic format:
try{ //Monitor code for possible exceptions }catch(exception type 1 variable){ //handle exception }catch(exception type 2 variable){ //handle exception }...
Exception handling principle:
1. Put the code that may go wrong into the try code block and encapsulate it as an object.
2. Received by the exception object in (Exception e) behind the catch.
3. After receiving, execute the code of the code block behind the catch.
4. The code behind the try-catch is executed normally.
Notice:
1. When the code in the try code block has no exception, the code in the catch is not executed.
2. When the code in the try code block has an exception, catch catches it, and the code behind the exception code in the try code block is no longer executed.
3. The code form behind the catch of the exception handling method:
Nothing can be written in the catch code block;
The prompt information can be customized in the catch code block;
Print exception information, use e.printStackTrace(), e.toString(), e.getMessage(), throw e
4. Under what circumstances, the code behind try...catch... is no longer executed?
When using throw in the catch code block to throw an exception;
There is no normal exception capture in the catch code block;
When there is a return in the try code block;
5. Under what circumstances, the code behind try...catch... must be executed?
Just put the code that must be executed into finally
6. What is the execution order of return and feinally?
Execute finally first and then return;
7.finally usage scenarios
When closing the database resource;
When closing the IO stream resource;
When closing the Socket resource;
8. When using System.exit() in the try code block to terminate the code of the virtual machine, the code in finally will not be executed.
Recommended format: Exception can catch some exception types
try{ //Code that may throw exceptions }catch(Exception e){ e.printStackTrace();//Print exception stack information directly }
#The principle of multiple Catch
When an exception occurs in the try, match the exception with the exception type behind the catch once, and execute the catch statement consistent with the exception type in the try. Once one of the catches is executed, the other catches will be ignored. When arranging the order of catch statements, generally put subclass exceptions in front and parent class exceptions in the back.
3. The case of combining the former two: first use throws to throw to the method caller, and then use try...catch.. to catch the exception
3. Runtime exception handling mechanism:
1. Under normal circumstances, it can not be processed, and the program will throw RuntimeException by default.
2. According to the principles and rules, the processing method is to use try...catch... on the outermost layer to catch the exception.
public class Test{ public static void main(String[] args){ System.out.println("The program starts. . . .") try{ text(a:5, b:0); }catch(Exception e){ e.printStackTrace(); } } System.out.println("The program terminates. . .") } public static void test(int a, int b){ System.out,println(a); System.out.println(b); int c = a / b; System.out.println(c); }