This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge
1, Java exception class hierarchy diagram
2, Error, Exception
In Java, all exceptions have a common ancestor, the Java.lang.Throwable class.
The Throwable class has two important subclasses: Exception and Error, each of which has a large number of subclasses.
Exceptions can be handled by the program itself (try-catch), errors cannot be handled (only to be avoided);
Error
:Error
It’s an error that the program can’t handle. We can’t pass itcatch
To capture. Examples include Java Virtual machine running error (Virtual MachineErro), insufficient vm memory error (OutOfMemoryError), class definition error (NoClassDefFoundError), and so on. When these exceptions occur, the Java Virtual Machine typically selects thread termination.Exception
: Exceptions that can be handled by the program itself can be passedcatch
To capture.Exception
Can be divided intoInspected anomaly(must deal with) andNot checked for abnormalities(It may not be handled).- Inspected anomaly
- Java code is compiled if the checked exception is not
catch
/throw
If it’s processed, it won’t compile; - In addition to
RuntimeException
And its subclasses, otherException
Class and its subclasses are checked exceptions; - Common abnormalities are as follows:
IOException
,ClassNotFoundException
,SQLException
…
- Java code is compiled if the checked exception is not
- Not checked for abnormalities
- Java code can compile without handling unchecked exceptions.
RunntimeException
And its subclasses are collectively referred to as unchecked exceptions;- Such as:
NullPointerException
(null pointer exception),NumberFormatException
(String converted to number),ArrayIndexOutOfBoundsException
(array index out of bounds),ClassCastException
(Type conversion exception),ArithmeticException
(arithmetic error), etc
- Inspected anomaly
3, try-catch – finally
-
Try block: used to catch an exception. It can be followed by zero or more catch blocks. If there is no catch block, a finally block must follow.
-
Catch block: for handling exceptions caught by a try;
-
Finally block: Statements ina finally block are executed regardless of whether an exception is caught or handled. When a return statement is encountered ina try or catch block, the finally block is executed before the method returns
public static int test(a){ try{ return 5; } catch (Exception e){ e.printStackTrace(); } finally{ return 8; }}// The final return is: 8 Copy the code
** Finally will not be executed in the following three special cases:
- in
try
或catch
Using a piece ofSystem.exit(0)
Exit the program; - The thread in which the program is running dies.
- Close the CPU.