Home > Java > javaTutorial > Java Improvement Chapter (16)-----Exception (1)

Java Improvement Chapter (16)-----Exception (1)

黄舟
Release: 2017-02-10 11:41:08
Original
1151 people have browsed it

The basic philosophy of Java is "poorly structured code will not run"! ! ! ! !

If a great achievement is lacking, its use will not be harmful.

##, it is endless.

##         There is no perfect thing in this world. No matter how meticulous and careful the perfect thinking is, we cannot consider all the factors. This is the so-called A wise man will make a mistake every time he thinks. In the same way, the computer world is not perfect. Abnormal situations can occur at any time. All we need to do is to avoid those exceptions that can be avoided and deal with the exceptions that cannot be avoided. Here I will record how to use exceptions to program a "perfect world".

           1. Why use exceptions

First of all, we can make it clear that the exception handling mechanism can ensure the robustness of our program and improve the system availability. Although we don't particularly like to see it, we can't help but recognize its status and role. Abnormalities indicate that there is a problem with the program, which helps us correct it in time. In our programming, exceptions may occur at any time and anywhere for any reason. When there is no exception mechanism, we handle it like this:Use the return value of the function to determine whether an exception has occurred. (This return value is usually agreed upon.) The program calling the function is responsible for checking and analyzing the return value. Although exception problems can be solved, there are several shortcomings in doing so:

##           1. Easily confused. If it is agreed that the return value is -11111, it indicates an exception, then what if the final calculation result of the program is really -1111?

               2. The code has poor readability. Mixing exception handling code with program code will make the code less readable.

​​ 3. Analyzing exceptions by calling functions requires programmers to have a deep understanding of library functions.

        The exception handling mechanism provided in OO is a powerful way to provide code robustness. Using the exception mechanism can reduce the complexity of the error handling code. If you do not use exceptions, you must check for specific errors and handle them in many places in the program. If you use exceptions, you do not have to use them in the method. Check at the call site because the exception mechanism will ensure that the error is caught and the error only needs to be handled in one place, the so-called exception handler. This approach not only saves code, but also separates the code that outlines what to do during normal execution from the code that says "what to do if something goes wrong." In summary, the exception mechanism makes reading, writing, and debugging code more organized than previous error handling methods. (Excerpted from "Think in java》).

##                                                                                                                                                                                                                      I always heard the teacher always say to remember to add exception handling where there may be errors. I didn’t understand it at the beginning, and sometimes I thought it was just unnecessary. , Now as I continue to deepen and write more codes, I gradually understand that exceptions are very important.

                                                                                                                                                                                                An exception refers to a problem that prevents the current method or scope from continuing to execute.. One thing must be made clear here: the exception code is wrong to some extent. Although Java has an exception handling mechanism, we cannot look at exceptions from a "normal" perspective. The reason for the exception handling mechanism is to tell you: something may or has already happened here. If an error occurs, your program has an abnormal situation, which may cause the program to fail!

             So when will an exception occur? Only if the program cannot run normally in your current environment, that is to say, the program can no longer solve the problem correctly, then it will jump out of the current environment and throw an exception. After throwing an exception, it does a few things first. First, it will use new to create an exception object, then terminate the program at the location where the exception is generated, and pop up the reference to the exception object from the current environment. The exception handling mechanism will take over the program and start looking for an appropriate place to continue executing the program. This appropriate place is the exception handler. Its task is to recover the program from the error state so that the program can either be executed in another way. Or just keep doing it.

##           In general, the exception handling mechanism is that when an exception occurs in the program, it forcibly terminates the program, records the exception information, and feeds this information back to us. Let's determine whether to handle the exception.

Three, abnormal system

# java provides us with a perfect abnormal processing mechanism, so that we can be more more Focusing on our program, we need to understand its architecture before using exceptions: as follows (this picture is taken from: http://www.php.cn/).



#​​​ From the picture above It can be seen that Throwable is the super class of all errors and exceptions in the Java language (everything can be thrown). It has two subclasses: Error and Exception.

##        Error is an error that cannot be handled by the program, such as OutOfMemoryError, ThreadDeath, etc. When this happens, the only thing you can do is to let it go and leave it to the JVM To handle, but the JVM will choose to terminate the thread in most cases.

          Exception is an exception that the program can handle. It is divided into two types of CheckedException (checked exception), one is UncheckedException (unchecked exception). Among them, CheckException occurs during the compilation phase, and try...catch (or throws) must be used, otherwise the compilation will not pass. UncheckedException occurs during runtime and is uncertain. It is mainly caused by logic problems of the program and is difficult to troubleshoot. We generally need to look at the overall situation to find such abnormal errors, so we need to be careful in program design. Think about it, write the code well, and try to handle exceptions as much as possible. Even if an exception occurs, you can try to ensure that the program develops in a favorable direction.

##        

So: Use checked exceptions (CheckedException) for recoverable conditions, for program errors (the implication is that it is not recoverable, the big mistake has been made ) using runtime exception (RuntimeException).

#         There are too many exception classes in Java, and the causes are ever-changing, so I will sort out the next blog post and count the exceptions that often occur in Java. I hope you will pay attention! !                                                                                                                            Words: The most true dependence in the world is when you are trying and I am catching. No matter how angry you are, I will bear it silently and deal with it quietly. For beginners, exceptions are try...catch (I also thought so when I first came into contact with it, and when encountering exceptions, it is try...catch). Personally, I feel that try...catch is indeed the most used and most practical.

​​

The try block in the exception contains the code block where exceptions may occur, and the catch block handles the exception after catching the exception. Let’s look at the following examples first:

public class ExceptionTest {
    public static void main(String[] args) {
        String file = "D:\\exceptionTest.txt";
        FileReader reader;
        try {
            reader = new FileReader(file);
            Scanner in = new Scanner(reader);  
            String string = in.next();  
            System.out.println(string + "不知道我有幸能够执行到不.....");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("对不起,你执行不到...");
        }  
        finally{
            System.out.println("finally 在执行...");
        }
    }
}
Copy after login

这是段非常简单的程序,用于读取D盘目录下的exceptionText.txt文件,同时读取其中的内容、输出。首先D盘没有该文件,运行程序结果如下:

java.io.FileNotFoundException: D:\exceptionTest.txt (系统找不到指定的文件。)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at java.io.FileReader.<init>(FileReader.java:41)
    at com.test9.ExceptionTest.main(ExceptionTest.java:19)
对不起,你执行不到...
finally 在执行...
Copy after login

从这个结果我们可以看出这些:

1、当程序遇到异常时会终止程序的运行(即后面的代码不在执行),控制权交由异常处理机制处理。

2、catch捕捉异常后,执行里面的函数。

当我们在D盘目录下新建一个exceptionTest.txt文件后,运行程序结果如下:

1111不知道我有幸能够执行到不.....
finally 在执行...
Copy after login

11111是该文件中的内容。从这个运行结果可以得出这个结果:不论程序是否发生异常,finally代码块总是会执行。所以finally一般用来关闭资源。

在这里我们在看如下程序:

public class ExceptionTest {
    public static void main(String[] args) {
        int[] a = {1,2,3,4};
        System.out.println(a[4]);
        System.out.println("我执行了吗???");
    }
}
Copy after login

程序运行结果:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at com.test9.ExceptionTest.main(ExceptionTest.java:14)
Copy after login

各位请注意这个异常信息和上面的异常信息错误,为了看得更加清楚,我将他们列在一起:

java.io.FileNotFoundException: D:\exceptionTest.txt (系统找不到指定的文件。)
        Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
Copy after login

       在这里我们发现两个异常之间存在如下区别:第二个异常信息多了Exception in thread"main",这显示了出现异常信息的位置。在这里可以得到如下结论:若程序中显示的声明了某个异常,则抛出异常时不会显示出处,若程序中没有显示的声明某个异常,当抛出异常时,系统会显示异常的出处。

以上就是java提高篇(十六)-----异常(一)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template