abnormal
Abnormal concept
Exception: refers to the abnormal circumstances in the course of program implementation, arise, resulting in non-JVM normal stop.
In Java and other object-oriented programming language, a class is itself an exception, an exception is to create an exception object and throw an exception object. Java is a way to handle exceptions interrupt handling.
Abnormal system
In fact, exception mechanism to help us find the problem program, abnormal root class is java.lang.Throwable , under which there are two sub-categories:
java.lang.Error and java.lang.Exception, usually referred to refer to abnormal java. lang.Exception
java.lang.Throwable: Java language class is all the errors or anomalies of the superclass.
Exception: compile an exception , a problem compiling (Code) Java program appears
- RuntimeException: runtime exception, a Java program running in the process of emerging issues
- An exception is equivalent program had a small problem (fever), the anomaly may continue to dispose of (medication)
Error: Error
- Is equivalent to a program error had incurable illnesses, you must modify the source code, the program can continue
Resolve anomalies generated process
int[] arr = {1,2,3}; int e = getElement(arr,3);
1) access to an array of 3 index, and the index of the array is not 3, this time, JVM program will detect abnormal
JVM will do two things:
- 1.JVM creates an exception object depending on the cause of abnormal generate, this exception object contains an exception generated (content, cause, location)
new ArrayIndexOutOfBoundsException("3");
- 2. getElement method, there is no exception handling logic (try ... catch), then the JVM will throw an exception object to the caller of the method, main ways to handle the exception.
2) The method of receiving the main exception object, the main method is no exception handling logic, continue to be thrown to the caller object is the main method of treatment JVM
new ArrayIndexOutOfBoundsException ( "3");
3) JVM receives the exception object , do two things
new ArrayIndexOutOfBoundsException ( "3");
- 1. The exception object (content, cause, location) in red font printed on the console
- 2.JVM terminates the Java program currently in execution -> Terminal handling
Exception handling
Five key Java exception handling: the try, the catch, a finally, the throw, throws
throw keyword
role:
- You can use the keyword throw throw exceptions specified in the method specified in
Using the format:
the throw new new xxxException ( "the cause of the abnormality generation");
note:
- throw keyword must be written in the internal method
- throw keyword behind new Exception object must be an object or a subclass of Exception
- throw keyword specified exception object is thrown, we must deal with this exception object
- throw keyword is behind the creation of RuntimeException or a subclass of RuntimeException object, we can not deal with the default JVM to handle (print exception object, interrupt program)
- throw behind the creation of the keyword is to compile an exception (error when writing code), we must deal with this exception, or throws, or try ... catch
Static method Objects class
public static <T> T reguireNonNull ( T obj): Specifies an referenced object is not null.
Source:
public static <T> T reguireNonNull(T obj){ if (obj == null) throw new NullPointerException(); return obj; }
statement throws an exception
throws keyword : The first way of exception handling, to others deal with
the role:
- When the internal method throws an exception object, then we must deal with this exception object
- You can use the exception object throws keyword processing, will declare the exception object is thrown to the caller method of treatment (they do not deal with, and give them treatment), and ultimately to the JVM process -> interrupt processing
Using the format: use in the method declaration
Modifier return type method name (parameter list) throws AAAException, ... {BBBException the throw new new AAAException ( "causes" ); the throw new new BBBException ( "causes" ); }
note:
- throws keyword must be declared at the write method
- keyword throws back exceptions must be declared Exception or a subclass of Exception
- If more than one internal method throws an exception object, then throws back must also declare more than one exception
- If multiple exceptions thrown objects have parent-child class relationship, then you can directly declare an exception parent
- A statement calling the method throws an exception, we must deal with this exception object
- Either continue to use the throw statement throws, to the processing method of the caller, and ultimately to the JVM
- Either try ... catch to handle exceptions yourself
Catch the exception try ... catch
try ... catch: The second way of exception handling, exception handling their own
format:
try { possible exception code } the catch (Exception define a variable for receiving the try thrown exception object) { exception handling logic, after the exception object, how to deal with exception object generally in operation, will abnormal the information is recorded into a log } ... the catch (exception class name variable name) { }
note:
- try more than one exception may be thrown objects, then you can use multiple catch to handle these exception object
- If you try the abnormality occurs, it will perform exception processing logic in the catch, finished processing logic catch, and continue with the implementation of the code after the try ... catch
If the try is not abnormal, then it will not perform exception processing logic in the catch, after executing the code in try, the code continues after the try ... catch
the Throwable class defines a method for exception handling 3
- String getMessage () Returns the Throwable short description
- String toString () Returns a string message detail Throwable
- void printStackTrace () JVM print exception object, by default this method, the exception information is the most comprehensive print
finally block
format:
try { possible exception code } the catch (Exception define a variable for receiving the try thrown exception object) { exception handling logic, after the exception object, how to deal with exception object generally in operation, will abnormal the information is recorded into a log } ... the catch (exception class name variable name) { } the finally { regardless of whether an abnormality occurs will be executed }
note:
- finally not be used alone, it must be used with the try
- finally generally used for resource release (recycling), regardless of whether the program is abnormal, eventually need to release resources (IO)
- If finally there is the return statement, it will never return results finally in, to avoid this situation.
note:
- The method of the parent class does not throw an exception, an exception is thrown nor parent subclass overrides this method. At this subclass generate this exception can only capture process, you can not declare thrown.
- What kind parent exception, a subclass exception is what
Custom exception class:
- Java exception classes provided, enough for us to use, you need to define yourself some exception classes
format:
public class XXXException the extends Exception | a RuntimeException { add an empty argument constructor adding a constructor with exception }
Examples:
Requirements: analog registering operation, if the user already exists, an exception is thrown and prompts: pro, the user has been registered.
analysis:
- Use array holds already registered user name (database)
- Use Scanner captures a registered user name entered by the user (front page)
- Defines a method for a user input registered user name to judge
- Traversal of data stored registered user name, access to each user name
- Using the acquired user name and user name entered by the user compare
true:
- User already exists, an exception is thrown RegisterException inform users of "pro, the user has been registered."
false:
- Continue to traverse Compare
- If the cycle is over, yet to find duplicate user name, user prompts, "Congratulations, the registration is successful!"
public class CaiNiao { // 1. Use array holds the user name has been registered (database) static String [] = {of usernames is "Novice", "vegetable", "fields" }; public static void main (String [] AGEs ) throws RegisterException { // 2. use Scanner captures a registered user name entered by the user (front page) Scanner sc = new new Scanner (System.in); System.out.println ( "Please enter the user name you want to register; " ) String username = sc.next (); CheckUserName (username); } // 3. define a method, for a registered user name entered by the user determines public static voidCheckUserName (String username) throws RegisterException { // iterate storing data registered user name, a user name for each acquisition for (String name: of usernames is) { // using the acquired user name and user name entered by the user Comparative IF (name .equals (username)) { // to true: the user already exists, RegisterException thrown exception, inform the user "parent, the user has been registered." the throw new new RegisterException ( "parent, the user has been registered." ); } } // If the cycle is over, yet to find duplicate user name, user prompts, "Congratulations, the registration is successful!" System.out.println ( "Congratulations, successfully registered!" ); } }