preface
Note: all tests in this article were performed in JDK1.8.
This article is my learning in Java exception handling this knowledge, do some summary and record.
If there is an incorrect place, please bear with us and give directions, thank you!
I. Introduction of exception mechanism
1.1 Basic Concepts
What is an exception? As the name suggests, it’s an abnormal phenomenon. A Java program runs abnormally. For example, we have the equation “10/0=?” We have to calculate, and we all know that 10 divided by 0 is meaningless, so if we use Java to calculate this equation, it will be abnormal.
1.2 Exception class system
Now that you understand the concept of exceptions, you need to know how they are represented in Java.
First you need to get to know the java.lang.throwable class, which is the superclass for all errors and exceptions in Java.
- Error: A Java virtual machine – related serious Error that cannot be resolved. For example, a system crash or a VIRTUAL machine error.
- Exceptions: Mainly programming errors that can be resolved by writing code. For example, the equation above that calculates 0 as a divisor.
So, the focus is on “exceptions” that can be solved by writing code.
1.3 Types of exceptions
Java.lang. Exception This is the superclass for all exceptions. Then we look at the java.lang.Exception class and see that there are several subclasses of the Exception class. So so many exception classes, how to distinguish and remember?
We classify program exceptions into two types based on whether they can be detected at compile time:
- RuntimeException: RuntimeException, also known as a non-detection exception.
- Other exceptions: Non-runtime exceptions, also known as detective exceptions.
The following are examples of non-detectable exceptions and detectable exceptions:
public class Test {
public static void main(String[] args) {
//1. Non-detection exception
System.out.println(10 / 0); / / compile successfully, the program can be run directly, but in running the code arithmetic exception happens (Java. Lang. ArithmeticException)
//2. Detection exception
FileInputStream file = new FileInputStream("d:/a.txt"); // The program cannot run directly because of a direct error at compile time}}Copy the code
Main subclasses of RuntimeException:
- ArithmeticException: ArithmeticException
- ArrayIndexOutOfBoundsException: array subscript cross-border anomalies
- NullPointerException: NullPointerException
- IllegalArgumentException: Invalid argument exception
- ClassCastException: Type conversion exception
- NumberFormatException: The number format is abnormal
1.4 Exception class architecture diagram
According to the types of exceptions listed above, the following structure diagram of exception classes can be formed:
Second, exception handling
Before you start, why do you need exception handling?
If an exception occurs in a program and is not handled, the execution of the program will be interrupted. Once an exception occurs, the statement after the exception will not be executed, but directly ends the program.
2.1 Exception avoidance
Run-time exception avoidance can be done with if conditional statements, and we’ll look at some of the most common subclasses above.
First, we encounter the following three exceptions:
public class ExceptionAvoid {
public static void main(String[] args) {
// An arithmetic exception occurs
int a = 10;
int b = 0;
System.out.println(a / b);
// Array index out of bounds exception occurs
int[] arr = new int[3];
int c = 3;
System.out.println(arr[c]);
// a null pointer exception occurs
String str = null; System.out.println(str.length()); }}Copy the code
Use the if condition statement to avoid exceptions:
public class ExceptionAvoid {
public static void main(String[] args) {
int a = 10;
int b = 0;
// Avoid arithmetic exceptions
if (0! = b) { System.out.println(a / b); }int[] arr = new int[3];
int c = 3;
// Avoid out-of-bounds array subscript exceptions
if (c >= 0 && c < 3) {
System.out.println(arr[c]);
}
String str = null;
// Avoid null pointer exceptions
if (null! = str) { System.out.println(str.length()); }}}Copy the code
Disadvantages: Although if conditional statements are good for exception avoidance, too many can lead to long code and poor readability.
2.2 Exception catching
Concept: The program may occur in the exception to capture processing, if the program exception, will be captured, some custom operations.
Syntax format:
try{code where an exception may occur}catch(Exception type references variable name) {code for handling exceptions}finally{code to execute whether or not an exception occurs} Note:catchThere can be multiple code blocks,finallyCode blocks can go withoutCopy the code
If you do not want to use an if condition statement for exception avoidance, or if the exception is not a runtime exception, you can capture the exception as shown below.
public class ExceptionCatch {
public static void main(String[] args) {
// Runtime exception
int a = 10;
int b = 0;
try {
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception has occurred");
}
// Non-runtime exception
try {
FileInputStream fis = new FileInputStream("d:/a.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found exception occurred");
} finally {
System.out.println("This code must be executed."); }}}Copy the code
Process analysis:
If there is no exception in the try block, the program will not enter the catch block. Instead, it will complete the program in the try block.
public class ExceptionCatch {
public static void main(String[] args) {
int a = 10;
int b = 2;
try {
System.out.println("1");
System.out.println(a / b);
System.out.println("2");
} catch (ArithmeticException e) {
System.out.println("3"); }}} output:1
5
2
Copy the code
2. If an exception occurs on a line in a try block, the program will not continue in the try block. Instead, it will enter the catch block directly and complete the program in the catch block.
public class ExceptionCatch {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
System.out.println("1");
System.out.println(a / b);
System.out.println("2");
} catch (ArithmeticException e) {
System.out.println("3"); }}} output:1
3
Copy the code
3. The finally code block must execute whether or not an exception occurs and is caught, as shown in the following example:
public class ExceptionCatch {
public static void main(String[] args) {
int a = 10;
intb = ? ;try {
System.out.println("1");
System.out.println(a / b);
System.out.println("2");
} catch (ArithmeticException e) {
System.out.println("3");
} finally {
System.out.println("4"); }}} if b =0; The output result is:1
3
4If b =2; The output result is:1
2
4
Copy the code
4. If an exception occurs and is caught, the program will not be terminated.
public class ExceptionCatch {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
System.out.println("1");
System.out.println(a / b);
System.out.println("2");
} catch (ArithmeticException e) {
System.out.println("3");
} finally {
System.out.println("4");
}
System.out.println("5"); }} output:1
3
4
5
Copy the code
Ask the question: How do you resolve the possibility of multiple exceptions in your code?
The workaround: Use multiple catch blocks to catch possible exceptions, with Exception pockets in the last catch block.
public class ExceptionCatch {
public static void main(String[] args) {
try {
div(4.0);
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception has occurred");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Aberration of correction occurs.");
} catch (Exception e) {
System.out.println("Abnormal"); }}public static int div(int a, int b) {
int []arr = new int [a];
System.out.println(arr[4]);// Make the first exception
return a/b;// Make a second exception}} Note: There are more than onecatchIn a code block program, superclass exceptions cannot precede subclass exceptions, for example, Exception cannot precede ArithmeticException.Copy the code
2.3 Exception Throwing
Concept:
In special cases where an exception cannot be handled or is inconvenient to handle, the exception can be passed to the caller of the method. When an exception occurs in method execution, the underlying generation of an object class throws the exception code and subsequent code does not execute.
Syntax format:
Access Permission Returned Value Type Method name (Parameter list) throws exception type 1, exception type 2…. {method body; }
public void test(int a) throws Exception {}
Copy the code
Sample code:
public class ExceptionThrow {
public static void main(String[] args) {
try {
show();
} catch(IOException e) { e.printStackTrace(); }}public static void show(a) throws IOException {
FileInputStream fileInputStream = new FileInputStream("d:/a.txt"); fileInputStream.close(); }}Copy the code
According to the sample code, three problems are explained:
-
Sometimes, to centralize exception handling, we can throw an exception in the method where it exists, and then centralize exception handling at the end. Exception catching can only be handled directly in this method.
-
Catching instead of throwing is done in the main method because the main method throws the exception up to the JVM, which is not good for exception handling.
-
Exception low-level source in show method:
The FileInputStream constructor creates an instance of File.
② Enter the File class, you can see the underlying exception thrown.
Method overwritten to throw an exception
-
Exceptions that subclasses are not allowed to throw
- Exception larger than the parent class
- An exception that is equal to, but not the same as, its parent
-
Exceptions allowed to be thrown by subclasses
- Can throw the same exception
- Can throw smaller exceptions
-
A subclass may not throw an exception
2.4 Custom Exceptions
Concept:
When the program needs to express the age is not reasonable, the Java official does not provide this specific exception, the programmer needs to define the exception to describe.
Custom exception implementation:
Create a custom Exception class that inherits the Exception class or its subclasses
public class AgeException extends Exception {
public AgeException(a) {}public AgeException(String message) {
super(message); }}Copy the code
Custom exception classes use:
Create a Person class that throws a custom exception in the setAge method.
public class Person {
private String name;
private int age;
public Person(a) {}public Person(String name, int age) throws AgeException {
setName(name);
setAge(age);
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge(a) {
return age;
}
public void setAge(int age) throws AgeException {
if (age > 0 && age < 200) {
this.age = age;
} else {
throw new AgeException("The age is not reasonable.")}}}Copy the code
Execute the main method to view the result:
public class Test {
public static void main(String[] args) {
try {
Person person = new Person("Bob".210);
} catch(AgeException e) { e.printStackTrace(); At person.setage (person.java:36)
at Person.<init>(Person.java:17)
at Test.main(Test.java:13)
Copy the code
Third, summary
An exception class architecture diagram
Three exception handling methods
A custom exception