Written on the front:
What is a video, and are you reading the documentation exciting?
What is a video and is it fast to read documents?
What is a video, and is it efficient to read documents?
1. Demo
Zhu Xiaoliang: Exceptions, that is, abnormalities, are various errors that occur when the program is running, such as:
public class Demo{
public static void main(String[] args){
int num = 2 / 0;//0不能作为除数,所以会产生异常
System.out.println("程序结束。。。。");
}
}
Outcome:
Zhang Xiaofei: I have encountered it many times before, can you explain specifically what this output means?
Zhu Xiaoliang: This is a must, and the above picture can be divided into 3 parts:
- ArithmeticException: is the exception type,
- / by zero: is the exception information
- (Demo.java:5) is where the exception occurs
Zhang Xiaofei: Understood
Zhu Xiaoliang: In addition, the program will terminate after an exception, so System.out.println("The program ended...") ); Does not run
Zhang Xiaofei: Oh, you don't say that you really didn't pay attention, I made a note of it
2. Introduction
Zhu Xiaoliang: In Java, the Throwable class is used to describe abnormal conditions when the program is running
Zhang Xiaofei: No, isn't the above exception ArithmeticException?
Zhu Xiaoliang: You're right, but all exceptions in Java are subclasses of Throwable, which are divided into two categories:
- Exception: Abnormal behavior that can be handled by modifying the code, such as ArithmeticException
- Error: It is generally a low-level problem of the system, and you cannot hear the code processing, such as memory overflow
What we mainly learn is how to handle exceptions such as Exception
3. Handle exceptions
Zhang Xiaofei: So, how to deal with exceptions?
Zhu Xiaoliang: You can use try catch to deal with it
1. try catch
Zhu Xiaoliang: Use the try catch code block to catch the specified exception and handle it, such as:
public static void main(String[] args){
try {
int num = 2 / 0;
}catch (Exception e){//catch 里面捕获指定的异常类型
//TODO 这里书写一些代码处理这种异常情况
//e.getMessage():获取异常信息
System.out.println("发现错误了。。。。" + e.getMessage());
}
System.out.println("程序结束。。。。");
}
Outcome:
, the program can end normally
Zhang Xiaofei: Can this code 'catch (Exception e)', which indicates the subtype of Exception, be captured?
Zhu Xiaoliang: Yes, then the code in catch will be executed
Zhang Xiaofei: You see I can't write like this
Zhu Xiaoliang: Of course, no problem, but in this case, if there are other exceptions in the code, you can't catch them, such as:
public static void main(String[] args){
try {
int[] arr = new int[2];
System.out.println(arr[2]);
int num = 2 / 0;
}catch (ArithmeticException e){
System.out.println("发现算术异常。。。。" + e.getMessage());
}
System.out.println("程序结束。。。。");
}
Outcome:
Explanation: Because we caught ArithmeticException, but the ArrayIndexOutOfBoundsException exception appeared, we did not follow the code in the catch
Zhang Xiaofei: That's the case, I understand
2. throws
Zhu Xiaoliang: Let's take a look at the throws keyword
Zhang Xiaofei: What is this for?
1. Demo
Zhu Xiaoliang; If you don't want to use try catch to handle exceptions, you can declare the exception with the throws keyword, for example:
//throws 写在方法上,用来声明异常
public static int div(int a, int b) throws Exception{
return a / b;
}
Zhang Xiaofei: This is ???
Zhu Xiaoliang: It is to remind the caller that this method may be abnormal
Zhang Xiaofei: You mean you need to use try catch when calling this method?
Zhu Xiaoliang: Yes, whoever calls who handles, then the place to call this method should be:
public static void main(String[] args){
try{
div(2,0);
}catch (Exception e){
//这里处理异常
}
}
Zhang Xiaofei: What if the caller doesn't want to deal with it either?
Zhu Xiaoliang: Then continue throws, such as:
Zhang Xiaofei: At this time, if there is an abnormality, who will deal with it?
Zhu Xiaoliang: The JVM handles it itself
2. Multiple abnormalities
Zhu Xiaoliang: In addition, throws can declare a variety of exceptions, but separate them with commas, such as:
Zhang Xiaofei: In that case, what should I do there?
Zhu Xiaoliang: If multiple exceptions are declared, catch should also have multiple exceptions to ensure that each exception can be cath and handled, such as:
public static void main(String[] args){
try{
div(2,0);
}catch (ArrayIndexOutOfBoundsException e){
}catch (ArithmeticException e){
}
}
//throws 写在方法上,用来声明异常
public static int div(int a, int b) throws ArrayIndexOutOfBoundsException, ArithmeticException{
return a / b;
}
Zhang Xiaofei: So it is
Zhu Xiaoliang: It can also be optimized
Zhang Xiaofei: Oh? How to optimize?
Zhu Xiaoliang: Because the above exceptions are all subclasses of Excepetion, just catch an Excetion directly, such as:
Zhang Xiaofei: Understood
3. Common methods
Zhu Xiaoliang: Let's talk about the common method in Exception
1. getMessage()
Zhu Xiaoliang: getMessage(), used to get exception information, has already been demonstrated, so I won't say more
Zhang Xiaofei: Okay
2. toString
Zhu Xiaoliang: toString(), convert the exception to string output, you can try it
Zhang Xiaofei: I tried it, take a look
Outcome:
3. printStackTrace
Zhu Xiaoliang: printStackTrace(), print abnormal stack information, this function is more useful
Zhang Xiaofei: Is that so? Like what:
Outcome:
Zhu Xiaoliang: That's right, in the picture above, the specific location of the error is shown
4. Throw keyword
Zhu Xiaoliang: Next, let's look at the throw keyword
Zhang Xiaofei: Well, didn't you just say that?
Zhu Xiaoliang: See clearly, what I just said was throws, and now it is throw, which is different
Zhang Xiaofei: Oh oh, what does this throw mean?
Zhu Xiaoliang: throw, used to throw specified exceptions, such as:
public static void main(String[] args){
try {
int num = div(2,0);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int div(int a, int b) throws Exception{
if(b == 0){
//通过 throw 关键字,抛出指定的异常,
//当程序运行到这里后中断,下面的 return a/b; 不再运行
throw new ArithmeticException("小学没毕业吗?除数不能是0---"+b);
}
return a / b;
}
Outcome:
Zhang Xiaofei: It can be like this, but what is the use of this? Will you automatically throw an exception without throwing?
Zhu Xiaoliang: There are two advantages to this, first, you can customize the exception information
Zhang Xiaofei: Oh, indeed, our custom information is clearer, and secondly?
Zhu Xiaoliang: Second, you can throw other exceptions, such as:
Zhang Xiaofei: Understood
Zhu Xiaoliang: In addition, if you don't know what exception should be thrown, you can use Exception, such as:
Zhang Xiaofei: I tried it, it's problematic to throw this, you see
Zhu Xiaoliang: Because, only objects of the Throwable type can be thrown by throw
Zhang Xiaofei: So it is
Zhu Xiaoliang: Let's summarize the difference between throw and throws
- The location is different
- throws: Used in methods, after which multiple types of exceptions can be specified
- throw: Used inside a method, followed by a specific exception object
- The functionality is different
- throws: Declares an exception that tells the caller that there may be a problem
- throw: throws an exception, and the program is interrupted when it runs here
Zhang Xiaofei: Understood, but when do you usually use throw?
Zhu Xiaoliang: It is generally used to verify parameters, and throw an exception if the parameters are not correct
5. RuntimeException
Zhu Xiaoliang: Let's talk about RuntimeException
Zhang Xiaofei: What does this mean?
"RuntimeException, run-time exception, that is: the exception thrown when the program runs, which is a special son under Exception"
"Oh? How about a special law? ”
"In general, after throwing an exception in the code, the compilation will fail, for example:"
"This is where you need to use throws on the method to declare the exception, for example:"
Zhang Xiaofei: No, I didn't use throws just now, and I didn't fail to compile
Zhu Xiaoliang: Because IllegalArgumentException is a subclass of RuntimeException
- Use throw to throw runtime exceptions, which do not need to be declared on methods
Zhang Xiaofei: So it is
Xiaofei Zhang: So, ArithmeticException ArrayIndexOutOfBoundsException, is it also a runtime exception?
Zhu Xiaoliang: Yes
Zhang Xiaofei: Why is that? Wouldn't it be better to use throws, and the caller needs to use try catch?
If it is not declared, the caller may forget to use try catch, which makes the program prone to errors
Zhu Xiaoliang: You are right, but when a RuntimeException appears, there is usually a problem with the code written by the caller
The purpose of this is to stop the program and let the caller modify the code
Zhang Xiaofei: That's how it is
Zhu Xiaoliang: Because of RuntimeException, you can divide Exceptions into two categories - inspected and untested
Zhang Xiaofei: What does this mean?
Zhu Xiaoliang: Let me explain it to you
- Detected exception: At compile time, to force the exception to be checked, this exception needs to be caught through try catch or declared on the method using throws, otherwise it cannot be compiled
- Non-tested exceptions: At compile time, there is no need to force the exception to be checked, and this exception can be caught or thrown without display
Zhang Xiaofei: So, RuntimeException is a non-test exception?
Zhu Xiaoliang: That's right, under Exception, RuntimeException is a non-tested exception, and the others are tested abnormalities
Zhang Xiaofei: Understood
6. Custom exceptions
Zhang Xiaofei: Custom exceptions – do you define a class to describe an exception?
Zhu Xiaoliang: Yes
Zhang Xiaofei: Java already provides exceptions, why customize exceptions?
Zhu Xiaoliang: Although Java uses Exceptions to describe abnormal situations when programs are running, there are many kinds of anomalies in reality
Its internal exception type (a subclass of Exception) may not meet the actual requirements, so you need to customize the exception
1. Demo
Zhu Xiaoliang: For example, define a method to do division operations, and if the divisor is less than or equal to 0, throw an exception that the divisor is negative
At present, there is no exception in Java where the divisor is negative, so customization is required
Example:
//自定义异常,注意:一般使用自定义异常都是起一些容易理解的名字,这样阅读性更好
class FuShuException extends Exception{
}
public class Demo{
public static void main(String[] args) {
try {
//除数传一个负数
int num = div(2,-1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int div(int a, int b) throws FuShuException {
if(b < 0){
throw new FuShuException();
}
if(b == 0){
throw new ArithmeticException("除数不能等于0。。。。。");
}
return a / b;
}
}
Zhang Xiaofei: There is no need to customize it, wouldn't it be better, you see
Zhu Xiaoliang: You are right, but sometimes you need to do different handling for different exceptions, such as:
Zhang Xiaofei: Understood
2. Customize the exception information
Zhang Xiaofei: You defined this FuShuException, you can't customize the exception information, IllegalArgumentException is possible
Aren't they all subclasses of Exception?
Zhu Xiaoliang: At this time, FuShuException lacks a constructor, such as:
FuShuException(String message){
super(message);//调用 super,设置异常信息
}
Zhang Xiaofei: So that's the case, I'll try it
3. Inherit the RuntimeException
Zhu Xiaoliang: In addition, currently FuShuException inherits Exception, which must be declared with throws on the method...
Zhang Xiaofei: This is simple, just inherit the RuntimeException directly, such as:
Zhu Xiaoliang: It seems that you have fully understood: non-test abnormalities
7. finally
Zhu Xiaoliang: Let's take a look at the finally code block
Zhang Xiaofei: What is this for?
1. Demo
Zhu Xiaoliang: Finally is a special code block used with try catch, such as:
public static void main(String[] args) {
try{
int num = 2 /0 ;
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("finally中的代码执行。。。。");
}
}
Outcome:
Zhu Xiaoliang: Did you find anything?
Zhang Xiaofei: The code in finally executes normally after the catch handling exception
Zhu Xiaoliang: That's right, that's the most important thing about it
2. The code in finally will definitely execute
Zhu Xiaoliang: Actually, the most important meaning of the finally code block is that the code in it will definitely execute
Zhang Xiaofei: Will it be implemented?
"That's right, even if the return statement is used in catch, finally executes, such as:"
public static void main(String[] args) {
try{
int num = 2 /0 ;
}catch (Exception e){
e.printStackTrace();
return;//catch中加上return语句,finally中的代码依然执行
}finally {
System.out.println("finally中的代码执行。。。。");
}
}
Outcome:
"Are there any exceptions?"
"There are exceptions to everything, and if you exit a JVM virtual machine, finally do not execute, for example:"
Outcome:
3. return 和 finally
Zhu Xiaoliang: I ask you a question, which is executed first, the statement after return or the statement in finally?
Zhang Xiaofei: Well...., wait for me to verify
public static void main(String[] args) {
show();
}
private static int show() {
try{
int num = 2 /0 ;
}catch (Exception e){
e.printStackTrace();
//return 后面调用一个方法
return test();
}finally {
System.out.println("finally中的代码执行。。。。");
}
return 1;
}
private static int test() {
System.out.println("返回一个0.....");
return 0;
}
Outcome:
Zhang Xiaofei: This is not the same as I expected, I thought that the code in finally was executed first?
Zhu Xiaoliang: Its execution process is like this:
- Execute the test method first and get a return value of 0
- Then execute the code in finally
- Finally, execute return and return 0
Zhang Xiaofei: Understood
8. Try catch finally combination
Zhu Xiaoliang: Here are a few common combinations of try catch finally
"The first type: try catch is used alone, this is the most common"
"The second: one try, many catches"
"The third: try and finally, no catch"
Zhang Xiaofei: "Is this okay?" Who handled the exception that was generated? ”
Zhu Xiaoliang: "Because there is no catch, the exception will be automatically thrown to the caller, but the code in finally will be executed"
9. Exceptions when methods override
Zhu Xiaoliang: When doing inheritance, there are a few points to pay attention to
First: If the parent class method or parent interface does not have throws exceptions, then the subclass overridden methods cannot throw exceptions either
class HeroException extends Exception{
}
class YaseException extends HeroException{
}
class DajiException extends Exception{
}
interface People{
void run();
}
class Person{
void eat(){
}
}
class child extends Person implements People{
//复写父类的方法
@Override
void eat()throws HeroException {
System.out.println("吃饭。。。。。");
}
//实现父接口的方法
@Override
public void run()throws HeroException {
System.out.println("走。。。。。");
}
}
Zhang Xiaofei: The above code failed to compile
Second: The exception type declared by the subclass method can only be the exception type declared by the parent class or its subtypes, such as:
Zhang Xiaofei: You mean that after the subclass overrides the run method, the declared exception can only be HeroException or its subtype?
Zhu Xiaoliang: Yes, there are 3 ways to be exact
First: declare a HeroException
Second: Declare a subtype of HeroException
Third: Do not declare exceptions
Zhang Xiaofei: What if you declare other types of exceptions?
Zhu Xiaoliang: Then the compilation will fail directly, such as:
Zhang Xiaofei: What if the parent method does not declare an exception?
Zhu Xiaoliang: This is the most special case, after the subclass overrides the method, you can declare a RuntimeException or Error, such as: