It's when people make mistakes, and when programmers have programming errors, they get an exception.
There are three types of programming errors: compile errors , logical Errors , run-time errors .
Compilation Error:
Reason: There is no rule resolution to follow the language: The compiler checks the discovery
Logical error:
Reason: The program was not implemented according to the intended programme
Workaround: Use debugging techniques to resolve this type of error
Run-time error:
Reason: There was an impossible operation during the program's operation
Workaround: Exception Handling
The following is a description of the Run-time error and workaround (Exception handling).
run-time Error (runtime error): Some irregularities during program operation
Common error (Throwable): Divisor is 0, array subscript out of bounds, file does not exist, memory is not enough, and so on.
These errors can be divided into fatal and Non-fatal exceptions.
Fatal errors (Error): The program entered the dead loop, recursive can not end, memory overflow and so on.
Such errors can only be resolved at the programming stage and cannot be resolved by the Run-time program itself. Can only rely on other programs to intervene, otherwise it will always be in an abnormal state.
Non-fatal Exception (Exception): divisor 0, operand out of range, file not present, missing class file to load, network connection interrupted ... This kind of error can be detected and processed, so the corresponding exception handling mechanism is produced.
Many exception classes are predefined in--java, and each exception class represents a Run-time error.
Some common (Exception):
NullPointerException NULL pointer exception
ArrayIndexOutOfBoundsException array out of bounds access exception
ClassNotFoundException attempted to access a class that does not exist at all
IOException Input/Output exception
Type conversion exception for numberformatexception error
Arraystoreexception When you deposit an array of incorrect type data
Arithmetic anomaly with a divisor of arithmeticexception 0
Java provides an exception handling mechanism that handles exceptions through object-oriented methods.
• If an exception occurs while the program is running, the program (or the Java Virtual machine) generates an object that represents the exception class (details that contain the exception) and hands it to the runtime system;
• The runtime system starts with the code that generates the object and looks through the call stack of the method, looking backwards until it finds a method that contains the corresponding processing code and gives the exception object to the method to handle the exception.
Mechanism for exception handling: Capturing and Handling exceptions using Try-catch-finally statements
1.Try statement block
• Put code in your program that might have an exception in a try block.
• When a statement in a try block throws an exception, the system will no longer execute the statement not executed in the try block and execute a matching catch block.
• If no statement in the try block throws an exception, the statement in the catch block is not executed after the program executes the statement in the try block.
The catch statement is skipped and the following program continues.
2,catch block
• Each try statement must be followed by one or more catch statements to catch the exception generated by the TRY statement block and handle it accordingly.
The goal of the catch clause is to resolve the "exception" situation and continue to run as if there were no errors.
A try example can have more than one catch block, and when multiple catch blocks are used, you need to be aware of the catch clause arrangement
Order--Special to general first, that is, subclasses are in front of the parent class. If the subclass is behind the parent class, the subclass will never
Will arrive. A try and its catch is a unit, and catch cannot catch exceptions thrown by other try declarations.
try cannot be used alone .
Whether an exception object can be received by a catch block is primarily seen in the exception object and in the catch block declared
The matching of exception classes, which are accepted when they meet any of the following conditions:
An exception object is an instance of an exception class declared in a catch block;
An exception object is an instance of a subclass of an exception class declared in a catch block;
The exception object implements the interface of the exception class declared in the catch block.
FINALLY statement block
In some cases, regardless of whether an exception occurs, some statements need to be processed, and the statements
into the finally statement block. The code contained in the finally statement is executed under any circumstances.
A try statement has at least one catch statement or finally statement to match, but a matching
A catch can have multiple, and a finally statement can have only one, and a finally statement is not necessary.
Format:
try{//Generate exception statement}
catch (Exception Class 1 variable)
{
Exception handling code
}
catch (Exception Class 2 variable)
{
Exception handling code
}
[finally{}]
Exceptions are classes so you can create and throw them artificially (throwable) as needed
If the code in a method may generate an exception at run time, but is not necessary in this method, or is unsure how to handle such an exception, you can use the throws declaration to discard the exception;
Indicates that the method will not handle such an exception, which is handled by the caller of the method;
That is, the system will look for the appropriate exception handling code in the upper method body that calls the method, and no longer proceed with the normal process of the method.
Syntax format: Throw exception class object;
Example: IOException e = new IOException (); Throw e;
The program terminates immediately after executing the throw statement, and then looks out from within all the try blocks that contain it
Contains a catch clause that matches its type.
Declaring a format for discarding exceptions
Type method name ([parameter table]) throws exception type, ...
{//method body;}
Custom exception classes: Although Java's built-in exception handling can handle most common errors, users still need to build
Own exception types to handle special cases. You can then define your own by creating a exception subclass of
The exception class.
The exception class does not define any methods of its own. But it inherits some of the methods provided by Throwable.
Format: class name extends Exception
{ ... ... }
In Java, the following factors need to be considered for handling exceptions:
If an exception event is generated at run time and there is no exception object corresponding to the exception event in the JDK API, you should create an exception object for the user-defined type.
If you can predict the type of an exception object and the exception occurs when the program is running, it is recommended that you apply the system exception type defined in the JDK API and that the exception object of this type can be thrown by the JVM.
If you cannot determine the type of the exception object and the timing of the occurrence, you should take a system type exception object and be processed by the JVM.
Exceptions to the types of array bounds, illegal variables, and so on that result from application design errors, if all types of exception objects are captured, the overhead is increased and the efficiency of the program is reduced, and it is recommended that the application not capture such exceptions and leave it to the JVM for processing.
For code that implements input/output processing, network communication, and database access, the exception object must be captured and processed.
Starting with the JDK1.4 version, the Java language introduced an assertion (assert) mechanism.
Purpose: Program debugging
When you test your code or debug a program, you always make assumptions that are used to capture in code
These assumptions.
Representation: An assertion is a statement in a program that checks for a Boolean expression
A correct program must ensure that the value of this Boolean expression is true;
If this value is False, the program is already in an incorrect state, the system gives a warning or exits
If there is no assertion mechanism, Java programs typically use IF-ELSE or switch statements for variable state checks.
Disadvantages:
Because the data types that are checked are not exactly the same, the statement form is not uniform.
Because the check is only applied to the test phase, and the if-else or switch statement will still work after the release,
If eliminating the code means annotating or deleting the code, if the code is large, it means that the work is heavy and risky.
Advantages:
Java programmers deal with stateful inspection problems in a unified way;
The assertion simply shuts down the feature when it is released.
The assertion is closed by default, so before the assertion is used,
The assertion function needs to be turned on first, by means of:
Java–ea MyClass or
Java–enableassertions MyClass to turn off assertion functionality:
Java–da MyClass or
java–disableassertions MyClass Note: Assertion checking is usually turned on during development and testing. For
Improved performance, the assertion check is usually turned off after the software is released.
The syntax format is: Assert Expression1
When executing to an Assert statement, if the value of Expression1 is true, the program executes normally, and if the value is false, the statement creates a assertion error object and throws the object.
Format: Assert Expression1:expression2 When an assertion fails, the system automatically passes the Expression2 value to the newly created Assertionerror object, which is then converted to a message string to save for more More targeted inspection of failure details.
When do you use the assertion:
Generally, assertions are used to check for key values, and these values have a significant effect on the entire program, or on the completion of local functionality.
Assertion expressions should be short , understandable , and if you need to evaluate complex expressions, you should use a function meter
Count
Case of using assertions
• Check control Flow: In If-else and switch statements, you can add a control tributary that should not occur
Assert statement. If this happens, the assert can be checked out.
• Check input parameters for validity before private method calculation, for some private methods, require input full
Enough specific conditions, you can use assert at the beginning of the method to check the parameters;
• For public methods, assertion checking is not usually used
Check whether the method results are valid after the method is calculated
• Check program invariants