Java: Exception capture and handling, do you understand?

The concept of exception:

An exception is an instruction stream that causes a program to be interrupted. If the exception is not handled correctly, it may cause the program to be interrupted and cause unnecessary losses.

Classification of exceptions:

Throwable is the parent class of all exceptions

Error:

Serious problem. After this problem occurs, it is generally not processed for the written code, and it is usually a problem thrown by Jvm.

Exception:

RuntimeException:

Runtime exceptions are both this class and its subclasses. This exception is not handled and can be compiled and passed, but errors will occur at runtime.

Except RuntimeException:

This type of exception is called a compile-time exception. This type of exception must be handled, and it will not run unless it is handled.

The structure of the exception:

This is an unusually common structure:

try{
    
    

​       可能出现异常的代码:

}catch(异常名称){
    
    

​		处理方案:

}finally{
    
    

​       关闭资源
}

Code case:

public class ExceptionTest {
    
    
    public static void main(String[] args) {
    
    
        int a =10;
        int b =0;
//        System.out.println(a/b);//分母不能为0,运行时异常,算数异常ArithmeticException。
//        System.out.println("end");
        try {
    
    
            System.out.println(a/b);
        }catch (RuntimeException e){
    
    
            System.out.println("除数不能为0");
        }finally {
    
    
            System.out.println("end");
        }
    }
}

Precautions:

try:

The less code inside, the better, because the exception handling mechanism is used when the code is wrapped by try, and Jvm needs to allocate additional resources to the mechanism.

catch:

There is at least one line of code

Multiple exception handling:

Code case:

public class ExceptionTest {
    
    
    public static void main(String[] args) {
    
    
        int a =10;
        int b =0;
        int c[]={
    
    1,2,3};
       // System.out.println(c[3]);//ArrayIndexOutOfBoundsException
        try {
    
    
            System.out.println(a / b);
            System.out.println(c[3]);
        }catch (ArrayIndexOutOfBoundsException e){
    
    
            System.out.println("数组索引越界");
        }
        catch (RuntimeException e){
    
    
            System.out.println("除数不能为0");
        }
        finally {
    
    
            System.out.println("end");
        }
    }
}

Three treatment methods:

1. One try and multiple catch

2. Multiple try corresponds to multiple catch, and multiple exceptions are thrown at the same time

3. A try...catch, but the exception in cath writes Exception, it can match all subclass exceptions

Advantages and disadvantages:

Advantages: some code omitted

Disadvantages: In the try block, if an exception occurs in the front, the following code will not be executed.

note:

1. When there are multiple exceptions at the same time, when the first exception is caught, it jumps directly to finally, and subsequent exceptions will not be processed.

2. If you don't know what kind of exception will occur in the try, you can use the exception name of the parent class to catch it (of course, you can be as specific as possible)

3. In multiple exceptions, there is a hierarchical relationship, from small to large catch

Exceptional new features (after jdk7):

public class ExceptionDemo3 {
    
    
    public static void main(String[] args) {
    
    
        int a =10;
        int b =0;
        int c[]={
    
    1,2,3};
        try {
    
    
            System.out.println(a / b);
            System.out.println(c[3]);
        }catch (ArrayIndexOutOfBoundsException|ArithmeticException  e){
    
    //同级异常可以通过|写在一起
            System.out.println("不好!有情况!");
        }
        finally {
    
    
            System.out.println("end");
        }
    }
}

Throwable:

Overview:

ThrowableThe class is the superclass of all errors or exceptions in the Java language.
Only when the object is an instance of this class (or one of its subclasses) can it be throwthrown through the Java virtual machine or Java statement

Common methods:

①Return the detailed message string of this throwable.

public String getMessage()

② Return a brief description of this throwable.

public String toString()

③ Output this throwable and its trace to the standard error stream.

public void printStackTrace()

④ Output this throwable and its trace to the specified output stream.

public void printStackTrace(PrintStream s)

Code case:

/**
 * Throwable
 *
 */
public class ExceptionDemo4 {
    
    
    public static void main(String[] args) {
    
    
     int a=0;
     int b=10;
     try{
    
    
         System.out.println(b/a);
     }catch (Exception e){
    
    
         System.out.println(e.getMessage());//返回此 throwable 的详细消息字符串。
         System.out.println(e);//调用toString方法,打印异常类名和异常信息。
         e.printStackTrace();//获取异常类名和异常信息,还有异常在程序中出现的问题,返回值void
     }
    }
}

throws与throw:

throws:

Overview:

When defining the functional mode, the problems that arise need to be exposed and let the caller handle them. Then it needs to be identified on the method by throws.

format:

Permission modifier return value type method name () formal parameter list) throws exception type 1, exception type 2...{}

note:

1. Throws must follow the method brackets
2. In general, throws should not follow main

Compile-time and runtime exceptions:

Compile-time exception: Whoever calls this method in the future must handle the exception.
Runtime exception: Whoever calls the method in the future may not necessarily handle the exception.

Code case:

public class throwsTest {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            method();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
    public static void method()throws Exception {
    
    
        int a =0;
        int b =10;
        System.out.println(b/a);
    }
}

throw

Overview:

When a certain situation occurs inside the function method, the program cannot continue to run, and when a jump is needed, the exception object is thrown with throw.

Code case:

public class throwDemo {
    
    
    public static void main(String[] args) {
    
    
        method();
    }
    public static void method(){
    
    
        int a=10;
        int b=0;

        if(b==0){
    
    
            throw new ArithmeticException();
        }else {
    
    
            System.out.println(a/b);
        }
    }
//    public static void method() throws Exception {
    
    
//        int a=10;
//        int b=0;
//
//        if(b==0){
    
    
//            throw new Exception();
//        }else {
    
    
//            System.out.println(a/b);
//        }
//    }
}

the difference:

throws

① Used after the method declaration, followed by the abnormal class name

②Can be followed by multiple exception class names, separated by commas

③ means that an exception is thrown, which is handled by the caller of the method

④throws represents the possibility of abnormalities, and these abnormalities may not occur

throw

① Used in the method body, followed by the abnormal object name

② Only one exception object name can be thrown

③ means that an exception is thrown, which is handled by the statement in the method body

④Throw throws an exception, and execution of throw must throw some kind of exception

Abnormal use:

Use exception difference:

If the function can handle the problem, try...catch

If it can’t be handled, hand it over to the caller, using throws

the difference:

If the program needs to continue running, use try……catch

If the program does not need to continue running, use throws

finally:

Features:

The statement body controlled by finally will be executed

Under special circumstances: JVM stopped running before finally executed, such as System.exit(0)

public class finallyDemo {
    
    
    public static void main(String[] args) {
    
    
        int a=10;
        int b=0;
        try {
    
    
            System.out.println(a/b);
        }catch (Exception e){
    
    
            System.out.println("分母不能为0");
            //System.exit(0);有这句则不执行finally
        }
        finally {
    
    
            System.out.println("结束啦");
        }
    }
}

effect:

Used to release resources, which will be seen in IO stream operations and database operations.

Interview questions:

①The difference between final, finally and finalize?

final : the final meaning, you can modify classes, member variables, member methods.
Modified classes: classes cannot be inherited.
Modified variables: variables cannot be modified.
Modified methods: methods cannot be overridden.
Finally:
it is part of the exception and is used to release resources. Generally speaking, whether an exception occurs or not, finally executes.
finalize:
A method of Object, used for garbage collection

②If there is a return statement in catch, will the finally code be executed? If so, is the order before or after return? :

Yes, and execute before return.

To be precise, it is executed when finally is running in return. First, let return 200, but it has not yet returned. At this time, it is found that there is a finally statement, and the finally statement is executed. At this time, a=400, and the variable value is changed. But the path of return 200 has been formed and cannot be changed, so return 200

public class finallyDemo2 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(method());
    }
    public static int method(){
    
    
        int a=100;
        try {
    
    
            System.out.println(a/0);
        }catch (Exception E){
    
    
            a=200;
            return a;
        }finally {
    
    
            a=400;
            System.out.println(a);
        }
        return 0;
    }
}

Insert picture description here

Custom exception:

Overview:

Although there are many exception types in Java, it is only our common type and cannot cover all exceptions. In the development process, we will encounter a variety of exceptions. At this time, we have to use our own defined exception class.

Notation:

We only need to write an ordinary class, inherit Exception, or RuntimeException

①Inherited from Exception

②Inherited from RuntimeException

Code case:

public class MyException extends Exception {
    
    
    public MyException(){
    
    

    }
    public MyException(String s){
    
    
        super(s);//一定要访问父类的有参构造,这样才能把异常信息打印到控制台
    }
}
class Teacher{
    
    
    public void check(int score) throws MyException {
    
    
        if(score>100 || score<0){
    
    
            throw new MyException("成绩只能在0-100之间");
        }else {
    
    
            System.out.println("你输入的成绩没问题");
        }
    }
}
class Student{
    
    
    public static void main(String[] args) throws MyException {
    
    
        System.out.println("请输入一个成绩:");
        Scanner input =new Scanner(System.in);
        int score = input.nextInt();
        Teacher t = new Teacher();
        t.check(score);
    }
}

Precautions:

① When the subclass overrides the parent method, the method of the subclass must throw the same exception or the abnormal subclass of the parent (the father is broken, and the son cannot be worse than the father)

② If the parent class throws multiple exceptions, when the subclass overrides the parent class, it can only throw the same exception or a subset of it, and the subset cannot throw exceptions that the parent class does not.

③If the overridden method does not throw a compilation exception, then the method of the subclass must not throw a compilation exception. If a compilation exception occurs in the subclass method, the subclass can only try but not throw

public class MyException2 {
    
    
    public static void main(String[] args) {
    
    
        zi z = new zi();
        z.show();
        z.method();
    }
}
class fu{
    
    
    public void  show() throws ArrayIndexOutOfBoundsException{
    
    

    }
    public void  method(){
    
    
        
    }
}

class zi extends fu{
    
    
    @Override
    public void show() throws ArrayIndexOutOfBoundsException{
    
    
        super.show();
    }

    @Override
    public void method() throws ArithmeticException{
    
    
        int a =10;
        int b =0;
        System.out.println(a/b);
    }
}

Guess you like

Origin blog.csdn.net/zjdzka/article/details/110422940