Table of Contents
Three, abnormal system " > Three, abnormal system
Home Java javaTutorial Java Improvement Chapter (16)-----Exception (1)

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

Feb 10, 2017 am 11:41 AM
java abnormal

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)!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles