Several Java interview questions every day: Exception mechanism (Day 3)


Friendly reminder

The questions at the back are very boring. Some dramatic scenes and story characters are added to deepen the memory. PS: Click the article directory to jump directly to the specified location of the article.

Act 3,

Session 1) Abnormal Mechanism Interview Questions

[Interviewer Lao Ji, interviewer Pan An, interviewer Lao Wang]

Lao Ji: There are 60 interviews today, from nine o'clock in the morning to six o'clock in the evening. Let's get started quickly. 1. The difference between Error and Exception

Lao Wang: Is your surname Wang?
①The parent classes of the Error class and Exception class are both throwable classes.
②The Error class generally refers to problems related to virtual machines, such as system crashes, virtual machine errors, insufficient memory space, method call stack overflow, etc. The program itself cannot be used to recover and prevent, so it is recommended that the program be terminated.
③Exception class represents exceptions that the program can handle, which can be caught and possibly recovered. Exceptions should be handled as much as possible and should not be terminated arbitrarily.

Wong Lo Kat: Anyway, my surname is not Jia. You can ask the next question, Pan An.

Pan An: If there is a problem with the program, an exception can be thrown. What can we do if the country has a problem? The Eight Kings' Rebellion during the period of Emperor Hui of the Western Jin Dynasty led to Wu Hu's rebellion in China, and I was also killed in the Eight Kings' Rebellion. So: 2. Let’s talk about the simple principles and applications of the exception handling mechanism in Java.

Lao Wang: You are only thirty-two years old and you already have gray hair. It is not easy to be a Java programmer.
①Exceptions refer to abnormal situations or errors that occur when a Java program is running (not compiled). The exception handling mechanism is a mechanism for identifying and responding to errors.
②Java uses an object-oriented approach to handle exceptions. It encapsulates each exception that occurs in the program into an object. The object contains exception information. We can also customize the exception class (inherit Exception or RuntimeException) . The root class of all exceptions is java.lang.Throwable, and two subclasses are derived from Throwable: Error (generally not concerned) and Exception (reasonable exceptions that should be handled).
③Exceptions are divided into runtime exceptions and compile-time exceptions.
The compiler forces compile-time exceptions to be handled by try...catch or continue to be thrown to the upper-layer calling method with a throws statement, so compile-time exceptions are also called checked exceptions.
④Running exceptions can be caught with try catch or not handled, so the compiler is not forced to use try...catch to handle or declare with throws.

Pan An: 3. Common abnormalities

Lao Wang:ArithmeticException (arithmetic exception)
ClassCastException (class conversion exception)
IllegalArgumentException (illegal parameter exception)
IndexOutOfBoundsException (subscript out-of-bounds exception)
NullPointerException (null pointer exception)

Lao Ji: 4. Let’s talk about exception handling: throw, throws and try…catch…finally

Lao Wang:It is not a problem if exceptions are always thrown using throw. Exceptions must be handled. At this time, throws and try...catch...finally need to be used.

/*格式: try{
            //可能出现异常的代码
        }catch(异常类型1 对象名){
            //逻辑代码
        }catch(异常类型2 对象名){
            //逻辑代码
        }
 */
public class TestException_3 {
    
    
    public static void main(String[] args) {
    
    
        test2();
    }

 public static void test2() {
    
    
        /*
            运行时异常:数组下标越界异常
                java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
         */
        try {
    
    
            int[] arr = new int[10];
            System.out.println(arr[10]);
        } catch (Exception e) {
    
         //参数位置可能发生多态        万能捕获器       表现:Exception e = new ArrayIndexOutOfBoundsException();
            e.printStackTrace();    //打印堆栈信息 ==> 将异常对象所属的类型、原因、涉及的行数打印展示在控制台
//            System.out.println(e.getMessage());       //得到异常出现的原因
        }

        System.out.println("执行了");
    }
}


In the try...catch...finally structure, finally is defined at the last position, and the code that must be executed is defined inside finally. The code in finally will definitely be executed.

/*格式: try{
            //可能出现异常的代码
        }catch(异常类型1 对象名){
            //逻辑代码
        }catch(异常类型2 对象名){
            //逻辑代码
        }finally{
            //定义一定需要被执行的代码
        }
 */
public class TestException_3 {
    
    
    public static void main(String[] args) {
    
    
        test4();
    }
 public static void test4() {
    
    
        FileInputStream fis = null;
        try {
    
    
            fis = new FileInputStream("hello2.txt");
            int len;
            while ((len = fis.read()) != -1) {
    
    
                System.out.println((char) len);
            }
            int num = 10 / 0;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }finally {
    
    	//这里面的代码一定会执行
            try {
    
    
                if (fis != null) {
    
    
                    fis.close(); 
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        System.out.println("执行了");
    }
}

Exception declaration processing: throws (delayed processing): When a method generates an exception that it does not want to handle immediately, it needs to use throws in the head of the method to actively declare the exception, tell the caller that a problem may occur, and hand it over later. Processed externally to achieve the purpose of delayed processing. As follows: The exception in the m1 method is finally solved by the m3 method.

/* 关键字:throws	格式:
        public ... 返回值类型 方法名(形参列表) throws 异常类型1,异常类型2,...,异常类型n{
            //方法体
        }
 */
public class TestException_4 {
    
    
    public static void main(String[] args) {
    
    
        m3();
    }

    public static void m3(){
    
    
        try {
    
    
            m2();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    public static void m2() throws IOException {
    
    
        m1();
    }

    public static void m1() throws IOException {
    
    
        FileInputStream fis = new FileInputStream("hello.txt");
        int len;
        while ((len = fis.read()) != -1) {
    
    
            System.out.println((char) len);
        }
        fis.close();
    }
}


The throw keyword is used to explicitly throw exceptions in the program. What is throwing an exception? In order to clearly point out that this method does not catch this type of exception, other methods that call this method must catch and handle the exception. We use throws to explicitly throw (generate) this type of exception.

/*
    演示手动抛出异常对象=关键字:throw
 */
public class TestException_5 {
    
    
    public static void main(String[] args) {
    
    
        People p = new People("张三", 140);
        System.out.println(p);
        //...
    }
}
//------------------------------分割----------------------------
class People{
    
    
    private String name;
    private int age;
    public People() {
    
     }
    public People(String name, int age) {
    
    
        this.name = name;
        //数据合理性的校验
        if (age <= 0 || age > 130) {
    
    
//      System.out.println("年龄不合理...");  //打印信息
//      throw new RuntimeException("年龄有误!"); //抛出异常,因为是运行时异常可以处理也可以不处理
//      throw new Exception("年龄有误..."); //抛出异常,因为不是运行时异常所以必须处理
   throw new MyException("年龄有误...");//抛出异常,因为是运行时异常的子类可以处理也可以不处理
        } else {
    
    
            this.age = age;
        }
    }
    public String getName() {
    
    return name;}
    public void setName(String name) {
    
    this.name = name;}
    public int getAge() {
    
    return age;}
    public void setAge(int age) {
    
    this.age = age;}
    @Override
    public String toString() {
    
    
        return "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


Pan An: 5. The difference between final, finally and finalize

Lao Wang:
①Final is used to declare properties, methods and classes, which respectively means that properties are immutable, methods cannot be overridden, and classes cannot be inherited.
②Finally is part of the exception handling statement structure, which means it is always executed.
③finalize is a method of the Object class. When the garbage collector is executed, the finalize method of the recycled object will be called. The finalize() method does the necessary cleanup work before the garbage collector clears the object from the memory. For example, close the file, etc. The JVM does not guarantee that this method will always be called

Pan An: Let’s end the interview today. You failed. Go to another company for an interview.

Lao Wang: Why?

Pan An: Our company judges people by their appearance.

Supongo que te gusta

Origin blog.csdn.net/baomingshu/article/details/132799535
Recomendado
Clasificación