Questions about exceptions

1. What is an exception?

An exception is an unspecified event that interrupts the normal execution of a program. When an exception occurs, the normal execution flow of the program is interrupted. Under normal circumstances, a program will have many statements. If there is no exception handling mechanism, once an exception occurs in the previous statement, the following statements will not be able to continue execution. "

"With the exception handling mechanism, the program will not be interrupted when an exception occurs. We can capture the exception and then change the flow of program execution."

2. What is operation abnormality?

UnChecked exception: runtime exception, an exception that may be thrown after running

3. How to handle exceptions

(1) Use try, catch, and finally to catch and handle exceptions

A try block contains code that may throw an exception.

The catch block is used to catch and handle exceptions of specified types

The code in the finally block will be executed regardless of whether an exception occurs, and is used to release resources or clean up operations.

(2) Use throw and throws to throw exceptions

The throw keyword manually throws an exception object.

The throws keyword is used to specify the type of exceptions that may be thrown in the method declaration, indicating that the method may throw exceptions of this type and be handled by the caller.

public void divideZero(){
try{
System.out.println(1/0); // 抛出除0异常
}catch(ArithmeticException e){
// 在 catch 里捕获异常,
// 注意,异常一旦被捕获,就相当于没有异常了,因此程序可以继续向
后运行
}
}

try with resource

4. Checked and unchecked exceptions

Checked exceptions (checked exceptions) must be explicitly caught or thrown in the source code, otherwise the compiler will prompt you to perform corresponding operations; while unchecked exceptions (unchecked exceptions) are so-called runtime exceptions, which usually can Avoidance through coding does not require explicit catching or throwing.

5. Can the constructor use throws to throw exceptions? What is the difference between using and not using throws?

6. The difference between throw and throws

1) The throws keyword is used to declare exceptions, and its function is similar to try-catch; while the throw keyword is used to explicitly throw exceptions.

2) The throws keyword is followed by the name of the exception; and the throw keyword is followed by the exception object.

3) The throws keyword appears in the method signature, and the throw keyword appears in the method body.

4) The throws keyword can be followed by multiple exceptions, separated by commas; the throw keyword can only throw one exception at a time.

7. Can error be thrown?

The appearance of Error means that there are serious problems in the program, and these problems should no longer be handled by Java's exception handling mechanism. The program should crash directly, such as OutOfMemoryError, memory overflow, which means that the program is running When the memory requested is greater than the memory that the system can provide, an error occurs. The occurrence of this error is fatal to the program.

The occurrence of Exception means that the program has some controllable problems, and we should take measures to save it.

For example, the ArithmeticException mentioned before is obviously because the divisor is 0. We can choose to catch the exception and then prompt the user that the division by 0 operation should not be performed. Of course, a better approach is to directly judge the divisor. If If it is 0, the division operation will not be performed, but the user will be told to change a non-0 number to perform the operation.

8. Return can be used in try --catch --finally statements. Why is only the statement in finally output?

public class TryDemo {
    public static void main(String[] args) {
        System.out.println(test1());
    }
    public static int test1() {
        try {
            return 2;
        } finally {
            return 3;
        }
    }
}

Execution result: 3.

Try executes finally before returning. As a result, finally does not follow the routine and returns directly. Naturally, the return in try cannot be reached.

(2)

public class TryDemo {
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test() {
        try {
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            System.out.print("3");
        }
    }
}

Execution result: 31.

try, catch. The basic usage of finally is that the finally statement block will be executed first before return, so the 3 in finally is output first, and then the 1 in return is output.

(3)

public class TryDemo {
    public static void main(String[] args) {
        System.out.println(test1());
    }
    public static int test1() {
        int i = 0;
        try {
            i = 2;
            return i;
        } finally {
            i = 3;
        }
    }
}

Execution results: 2.

You may think that the result should be 3, because finally will be executed before return, and i is modified to 3 in finally, so shouldn't the final returned i be 3?

But in fact, before executing finally, the JVM will temporarily store the result of i, and then after finally is executed, it will return the previously buffered result instead of i, so even if i has been modified to 3, the final returned It is still the result 2 that was temporarily saved before.

9. Why custom exceptions

Why you need to customize exceptions:

Java has anticipated many exceptions, each of which is represented by a class. But if the exception class provided by java cannot meet your needs, you can define your own exceptions to meet your needs. In project development, corresponding exceptions are usually customized due to business needs. Customized exceptions make the exception information more accurate.

10. How to customize exceptions

Custom exception steps:

Step 1: Custom compile-time exceptions inherit Exception, and custom run-time exceptions inherit RuntimeException.

Step 2: Pass the exception description information to the exception parent class through the constructor

Step 3: Use throw to throw an exception object

Step 4: Handle exceptions

// 自定义异常
class MyException extends Exception{
public MyException(String message){
// 通过构造函数将异常描述信息传递给异常父类
super(message);
}
}
public class UserController {
public static void main(String[] args) throws MyException
{
int i=1 ,j = 0;
if(j ==0){
// 将自定义异常抛给虚拟机,让虚拟机去处理
throw new MyException("除数不能为0");
}
System.out.println("i / j = "+ i/j);
}
}

11. What is the difference between NoClassDefFoundError and ClassNotFoundException?

They are all caused by the system not being able to find the class to be loaded when running, but the triggering reasons are different.

  • NoClassDefFoundError: The program can find the dependent classes when compiling, but cannot find the specified class file at runtime, causing this error to be thrown; the reason may be that the jar package is missing or a class that fails to initialize is called.
  • ClassNotFoundException: This exception is thrown when the corresponding class cannot be found when dynamically loading a Class object; the reason may be that the class to be loaded does not exist or the class name is written incorrectly.

Secondly, exceptions such as IOException, ClassNotFoundException, and SQLException are all checked exceptions; exceptions such as RuntimeException and subclasses ArithmeticException, ClassCastException, ArrayIndexOutOfBoundsException, and NullPointerException are all unchecked exceptions.

Unchecked exceptions can not be handled explicitly in the program, just like the ArithmeticException mentioned before; but checked exceptions must be handled explicitly.

12. Three situations in which a method ends its operation

When the code in the method completes execution, the method ends

After the return statement is executed in the method, the method ends

After an exception is thrown in the method, the method ends

Ava's exception handling is an important mechanism that can help us handle errors or exceptions that occur during program execution.

Exceptions are divided into two categories: Checked Exception and Unchecked Exception. Checked Exception needs to be explicitly handled or declared to be thrown in the code, while Unchecked Exception does not need to be explicitly handled or declared to be thrown in the code. Exception handling is usually handled using try-catch-finally blocks. You can also use the throws keyword to throw exceptions to the caller for processing.

The following is some summary of Java exception handling:

  • Use try-catch blocks to catch and handle exceptions to avoid program crashes due to exceptions.
  • You can use multiple catch blocks to catch different types of exceptions and handle them differently.
  • You can use the finally block to perform some necessary cleanup work, whether an exception occurs or not.
  • Exceptions can be thrown manually using the throw keyword, which is used to explicitly specify certain exception conditions in the program.
  • You can use the throws keyword to throw exceptions to the caller for processing, which is used to declare possible exceptions in the method signature.
  • Checked Exceptions are usually problems caused by external factors and need to be explicitly handled or declared thrown in the code.
  • Unchecked Exception is usually caused by internal logic or data exceptions in the program and can be left unhandled or handled when needed.
  • When handling exceptions, you should handle them according to the specific exception type. For example, you can try to reopen the file, re-establish the network connection, etc.
  • Exception handling should be carried out according to specific business requirements and design principles to avoid excessive catching and handling of exceptions, thereby reducing the performance and maintainability of the program.

Guess you like

Origin blog.csdn.net/pachupingminku/article/details/132588906
Recommended