@[toc]
1, abnormal
1.1 Exception Concepts
Exception: Simply put, an abnormal operation that causes the JVM to stop abnormally.
In object-oriented programming languages such as Java, an exception is itself a class, and to raise an exception is to create and throw an exception object. Java handles exceptions with interrupt handling.
Exceptions are not syntax errors, syntax errors, compilations fail, no bytecode files are produced, you can’t run at all.
1.2 Abnormal System
The root class of an Exception is java.lang.Throwable, which has two subclasses: Java.lang. Error and java.lang.Exception.
Common methods in Throwable:
1. Public void printStackTrace(): prints details about exceptions.
Contains the type of exception, the reason for the exception, and the location of the exception, both during development and debugging, using printStackTrace.
2, public String getMessage(): get the cause of the exception.
When the user is prompted, the cause of the error is prompted.
3, public String toString(): get the exception type and exception description (no need).
The easiest way to get an exception is to copy the simple class name of the exception into the API.
1.3 Anomaly Classification
When we say Exception, we mean Exception, because when it happens, we have to fix the code.
Classification of exceptions: Are exceptions checked at compile time or run time?
- Compile-time exception: Checked exception. At compile time, it checks and if no exception is handled, the compile fails. (such as date formatting exception)
- Runtime anomaly: a runtime exception. At run time, check for exceptions. Run exceptions are not detected by the compiler at compile time. (e.g., mathematical anomalies)
1.4 Exception Generation Process Analysis
To run the following program, the program produces an array index cross-border exception ArrayIndexOfBoundsException. Let’s use a diagram to explain how the anomaly occurs.
Utility class
public class ArrayTools {
// Retrieves the element from the given array with the given corner marker.
public static int getElement(int[] arr, int index) {
int element = arr[index];
returnelement; }}Copy the code
The test class
public class ExceptionDemo {
public static void main(String[] args) {
int[] arr = { 34.12.67 };
intnum = ArrayTools.getElement(arr, 4)
System.out.println("num=" + num);
System.out.println("over"); }}Copy the code
Diagram of the execution of the above procedures:
2. Handling of exceptions
The five keywords of Java exception handling are try, catch, finally, throw, and throws
2.1 Throwing an Exception Throw
When writing a program, a good programmer must consider the situation when the program goes wrong. For example, when defining a method, the method needs to accept parameters. Therefore, when calling a method to use the parameters received, the first need to determine the validity of the parameter data, if the data is illegal, we should tell the caller to pass in the valid data. You need to tell the caller by throwing an exception. This is where throw comes in handy!
In Java, we provide a throw keyword that throws a specified exception object. In order to
1. Create an exception object. Encapsulate some prompts (you can write your own).
2. The exception object can be told to and passed to the caller by using the keyword throw.
Throw summary
Throw is used in a method, followed by an exception object, using the format throw new exception class name (parameter); Passes the exception object to the caller and terminates execution of the current method.
Throw uses the following format:
throw new NullPointerException("Arr array to be accessed does not exist");
throw new ArrayIndexOutOfBoundsException("Index does not exist in array, out of range");
Copy the code
Examples of throwing use:
public class ThrowDemo {
public static void main(String[] args) {
// Create an array
int[] arr = {2.4.52.2};
// Find the corresponding element according to the index
int index = 4;
int element = getElement(arr, index);
System.out.println(element);
System.out.println("over");
}
/* * Find the corresponding element in the array */
public static int getElement(int[] arr,int index){
// Determine whether the index is out of bounds
if(index<0 || index>arr.length-1) {/* The method cannot continue after the exception object is thrown. Execution of the current method is terminated and the exception is notified to the caller. This is where exceptions are needed to solve the problem. * /
throw new ArrayIndexOutOfBoundsException("Dude, the horn tag is out of line.");
}
int element = arr[index];
returnelement; }}Copy the code
Throw effect analysis:
Let’s take a look at the run used by instances that don’t use throws
public static void main(String[] args) {
// Create an array
int[] arr = {2.4.52.2};
// Find the corresponding element according to the index
int index = 4; // Note that index 4 is out of bounds
int ele=arr[index];
System.out.println(ele);
System.out.println("over");
}
Copy the code
The results
throw
2.2 Objects non-null judgment
Remember that the Objects class consists of static utility methods such as null-save or null-tolerant, which in its source code throw an exception on the value of the object that is null.
Public static
T requireNonNull(T obj): Checks that the specified reference object is not null.
Error: null ();
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
Copy the code
2.3 Declaring exceptions throws
If there is a problem, we throw the problem description class, the exception, which returns the problem to the caller of the method.
So what about the caller? One is to capture processing, the other is to continue to declare the problem out, using throws declaration processing.
Declare an exception: Identify the problem and report it to the caller. If a compile-time exception is thrown by a throw inside a method without catch handling (which is explained later), then you must declare it through throws for the caller to handle.
Throws summary
Throws the keyword is used on method declarations. The format is modifier return value type method name (parameter) throws exception class name 1, exception class name 2… {}, used to indicate that the current method does not handle an exception, but instead reminds the method’s caller to handle the exception (throws an exception).
Exception declaration code demo:
public class ThrowsDemo {
public static void main(String[] args) throws FileNotFoundException {
read("a.txt");
}
// If a problem occurs while defining a function, report it to the caller. You can declare it by using the throws keyword on methods
public static void read(String path) throws FileNotFoundException {
if(! path.equals("a.txt")) {// if it is not a.txt file
// I assume that if it is not a.tuck that the file does not exist is an error, that is, an exception throw
throw new FileNotFoundException("File does not exist"); }}}Copy the code
Throws is used to declare exception classes. If multiple exceptions may be generated in the method, throw multiple exception classes after the method, separated by commas (,).
public class ThrowsDemo2 {
public static void main(String[] args) throws IOException {
read("a.txt");
}
public static void read(String path)throws FileNotFoundException, IOException {
if(! path.equals("a.txt")) {// if it is not a.txt file
// I assume that if it is not a.tuck that the file does not exist is an error, that is, an exception throw
throw new FileNotFoundException("File does not exist");
}
if(! path.equals("b.txt")) {
throw newIOException(); }}}Copy the code
Throws and throws a summary of the differences
Throw:
If the exception object is a non-runtimeException, throw the exception with the declaration of the method, that is, add a throw statement or process the exception with a try catch inside the method. Throw (); throw (); throw ()
Throws:
1, the definition method using throws say this method may throw some unusual 2, need to be done by way of the caller exception handling
2.4 Catch the exception Try… catch
If an exception occurs, it will terminate the program immediately, so we have to handle exceptions:
- Instead of processing, the method declares a throw, which is handled by the method’s caller (
throws
). - Used in a method
try-catch
To handle exceptions.
The try-catch method is to catch an exception.
Catch exceptions: In Java, exceptions are captured in specific statements that can be handled in a specified way.
Syntax for catching exceptions is as follows:
try{write code that may fail}catch(Exception type e){Code for handling exceptions// Record logs/print exception information/continue to throw exceptions
}
Copy the code
Try: Write code in this block that may raise an exception.
Catch: Used to catch an exception and process the caught exception.
Note: Neither try nor catch can be used alone; they must be used together.
The demo is as follows:
public class TryCatchDemo {
public static void main(String[] args) {
try {// When an exception is raised, there must be a way to handle it. Either capture or declare.
read("b.txt");
} catch (FileNotFoundException e) {// What do I need to define in parentheses?
// What exception is thrown in a try, and what exception type is defined in parentheses
System.out.println(e);
}
System.out.println("over");
}
/* * * We have a compile-time exception in this method */
public static void read(String path) throws FileNotFoundException {
if(! path.equals("a.txt")) {// if it is not a.txt file
// I assume that if it is not a.tuck that the file does not exist is an error, that is, an exception throw
throw new FileNotFoundException("File does not exist"); }}}Copy the code
How to obtain exception information:
The Throwable class defines some viewing methods:
1, public String getMessage(): getMessage(): getMessage(): getMessage();
2, public String toString(): Getexception type and exception description (no need).
3. Public void printStackTrace(): Prints stack trace information for exceptions and prints it to the console.
Contains the type of exception, the reason for the exception, and the location of the exception, both during development and debugging, using printStackTrace.
2.4 Finally code block
Finally: There is certain code that needs to be executed whether or not an exception occurs. In addition, some statements cannot be executed because exceptions cause program jumps. Finally solves this problem by storing code ina finally block that must be executed.
When must the code finally be executed?
When we open physical resources (disk files/network connections/database connections, etc.) in a try block, we eventually close the open resources when we’re done using them.
Finally syntax:
try… catch…. Finally: It needs to handle the exception itself and eventually close the resource.
Note: Finally cannot be used alone.
For example, in an IO stream, when a resource associated with a file is opened, the program eventually needs to close the resource regardless of the result.
Finally code reference is as follows:
public class TryCatchDemo4 {
public static void main(String[] args) {
try {
read("a.txt");
} catch (FileNotFoundException e) {
// a compile-time exception is thrown at runtime
throw new RuntimeException(e);
} finally {
System.out.println("Whatever the program is, it will be executed here.");
}
System.out.println("over");
}
/* * * We have a compile-time exception in this method */
public static void read(String path) throws FileNotFoundException {
if(! path.equals("a.txt")) {// if it is not a.txt file
// I assume that if it is not a.tuck that the file does not exist is an error, that is, an exception throw
throw new FileNotFoundException("File does not exist"); }}}Copy the code
Finally is not executed when the associated method exiting the JVM is called only ina try or catch, otherwise it will always be executed.
2.5 Finally code block and return statement
Another important point is that when a return statement is encountered ina try or catch block, the finally statement will be executed before the method returns. A finally statement can also have a return statement, but try to avoid a return statement (warning).
2.6 Exception Precautions
What about multiple exceptions using capture?
Multiple exceptions are handled separately.
Multiple exceptions are captured and processed multiple times.
Multiple exceptions are caught once and handled once.
Generally, we use a capture multiple processing mode, the format is as follows:
try{write code that may fail}catch(Exception type A e){WhentryIf A type A exception occurs incatchTo catch. Handle exception code// Record logs/print exception information/continue to throw exceptions
}catch(Exception type B e){WhentryIf a type B exception occurs incatchTo catch. Handle exception code// Record logs/print exception information/continue to throw exceptions
}
Copy the code
Note: This method of exception handling requires that the exceptions in multiple catches cannot be the same, and if there is a relationship between the exceptions in the catch and the parent class, then the child class exception should be handled in the catch above, and the parent class exception should be handled in the catch below.
Summary of abnormal attention:
-
Runtime exceptions thrown may not be handled. Neither catch nor declare a throw.
-
Avoid this situation by always returning the result in finally if there is a return statement in finally. Mentioned above too!
-
If the parent class throws more than one exception, the subclass overrides the parent class method, throwing the same exception as the parent class or a subclass of the parent class exception or not throwing an exception.
-
A superclass method does not throw an exception, and a subclass may not throw an exception when overriding the superclass method. The subclass generates the exception and can only catch and handle it, not declare it to throw it
3. Custom exceptions
3.1 an overview of the
Why custom exception classes are needed:
In Java, different exception classes represent specific exceptions. In development, there are always exceptions that SUN has not defined, so we define exception classes according to our business. For example, programmer hair number is negative, xiaoming exam results negative problems and so on.
In the previous program code, it is found that these exceptions are internal JDK defined, but the actual development will also appear a lot of exceptions, these exceptions are probably not defined in JDK, such as the number of programmer wife is negative, programmer Lao Wang IQ is negative. Can you define your own exceptions? The answer is yes!
What is a custom exception class?
Define exception classes in development based on the exception conditions of your business.
Define a custom business logic exception: RegisterException. A registered exception class.
How to define an exception class:
- Custom a compile-time exception: custom class and inherit from
java.lang.Exception
. - Customize a runtime exception class: Custom class and inherit from
java.lang.RuntimeException
.
3.2 Custom exception Exercises
For example, if the user name already exists, an exception will be thrown and the message “dear, the user name has already been registered.”
Start by defining a login exception class RegisterException:
// Service logic exception
public class RegisterException extends Exception {
/** * void parameter construct */
public RegisterException(a) {}/ * * * *@paramMessage indicates an exception message */
public RegisterException(String message) {
super(message); }}Copy the code
Simulate login operation, using array to simulate the data stored in the database, and provide the method to determine whether the current registered account exists.
public class Demo {
// An account already exists in the simulated database
private static String[] names = {"bill"."hill"."jill"};
public static void main(String[] args) {
// Call the method
try{
// Possible exception code
checkUsername("nill");
System.out.println("Registration successful");// If there is no exception, the registration is successful
}catch(RegisterException e){
// Handle exceptionse.printStackTrace(); }}// Check whether the current registered account exists
// This is a compile-time exception and is intended to be handled by the caller
public static boolean checkUsername(String uname) throws RegisterException {
for (String name : names) {
if(name.equals(uname)){// Throw a login exception if the name is inside
throw new RegisterException("Kiss"+name+"Already registered!"); }}return true; }}Copy the code
The user name does not exist and the login succeeds. The result is as follows:
4, come! And the big one
Read this article here is basic, blogger, I also don’t know how you absorbed, I have to responsible for you the duck, not finished just a matter of, so still feel let you consolidate cement is better, if you are able to make the following typical abnormal problem, explain abnormal knowledge can’t much problem for you, if you feel where is not particularly understand, Can tell me in time, who saw will be the first time to reply. Well, imagine what happens when this program runs
package com.gx.Expetion;
public class TestException {
public TestException() {
}
boolean testEx() throws Exception {
boolean ret = true;
try {
ret = testEx1();
} catch (Exception e) {
System.out.println("testEx, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx, finally; return value=" + ret);
return ret;
}
}
boolean testEx1() throws Exception {
boolean ret = true;
try {
ret = testEx2();
if(! ret) {return false;
}
System.out.println("testEx1111, at the end of try");
return ret;
} catch (Exception e) {
System.out.println("testEx1111, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx1111, finally; return value=" + ret);
return ret;
}
}
boolean testEx2() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 2; i >= 2 -; i--) {
c = b / i;
System.out.println("i=" + i);
}
return true;
} catch (Exception e) {
System.out.println("testEx2222, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx2222, finally; return value=" + ret);
return ret;
}
}
public static void main(String[] args) {
TestException testException1 = new TestException();
try {
testException1.testEx();
} catch(Exception e) { e.printStackTrace(); }}}Copy the code
Running results:
i=2
i=1
testEx2222, catch exception
testEx2222, finally; return value=false
testEx1111, finally; return value=false
testEx, finally; return value=false
Copy the code
If you feel where is not particularly understand, you can timely tell me, who see will be the first time reply!!
Up to now, many white students still don’t feel the blogger’s “if you die, you have to try and catch me.” The feel, right? All right, the blogger feels like the one who feels like the white one
/** * Put the ResultSet of multiple data into List
* @param rs ResultSet * @param obj Java class * @return */
public static <T> List<T> getResult(ResultSet rs, Class<T> obj) {
try {
List<T> list = new ArrayList<T>();
ResultSetMetaData Information about the name and type of the columns in a ResultSet.
ResultSetMetaData metaData = rs.getMetaData();
// Get the total number of columns
int count = metaData.getColumnCount();
/ / traverse the ResultSet
while (rs.next()) {
// Create an object instance
T instance = obj.newInstance();
for (int i = 1; i <= count; i++) {
//-- get the column name
String name = metaData.getColumnName(i);
// Change the column name format to Java naming format mainly for _ split cases such as user_id
name = toJavaField(name);
// Get the typeClass<? > type = obj.getDeclaredField(name).getType();//-- get setter methods
// Uppercase
String replace = name.substring(0.1).toUpperCase() + name.substring(1);
Method setMethod = obj.getMethod("set" + replace, type);
// Determine the type of data to read
if (type.isAssignableFrom(String.class)) {
setMethod.invoke(instance, rs.getString(i));
} else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) {
setMethod.invoke(instance, rs.getInt(i));
} else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
setMethod.invoke(instance, rs.getBoolean(i));
} else if (type.isAssignableFrom(Date.class)) {
setMethod.invoke(instance, rs.getDate(i));
}
}
list.add(instance);
}
return list;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
Copy the code
The above code is designed to reflect, generics, and exceptions. Catch ~, String class, JDBC related knowledge, most of these knowledge I have written articles, are interested in the small white students directly click the blue font into the article. Ahem… To get back to the point, have you noticed that the above code is used to capture many times, the format is as follows:
try{write code that may fail}catch(Exception type A e){WhentryIf A type A exception occurs incatchTo catch. Handle exception code// Record logs/print exception information/continue to throw exceptions
}catch(Exception type B e){WhentryIf a type B exception occurs incatchTo catch. Handle exception code// Record logs/print exception information/continue to throw exceptions
}
Copy the code
Note: This method of exception handling requires that the exceptions in multiple catches cannot be the same, and if there is a relationship between the exceptions in the catch and the parent class, then the child class exception should be handled in the catch above, and the parent class exception should be handled in the catch below.
This is the second time I’ve written this, so did you find a catch that didn’t quite catch?
Finally, the next two Java articles in this column are recommended for those who are interested
Understanding the upward and downward transition of polymorphism starts with “Mom, I want toasted yams”
Java inheritance starts from “My father is Li Gang”
Welcome to pay attention to my public number, discuss technology together, yearning for technology, the pursuit of technology…