Analysis of checked and non checked exceptions in Java programming

For exceptions caused by programming errors, or exceptions that cannot be expected to be caught by the program (dereference of a null pointer, array out of bounds, division by zero, etc.), in order to prevent developers from handling these exceptions, some exceptions are named non checking exceptions (i.e. those inherited from runtimeException) and do not need to be declared.

There are several differences between checked exception and unchecked exception. Whether the method signature needs to declare exception, whether the exception needs to be captured when calling the method, and the state of the JVM control program when the exception is generated.

Sun's "the java tutorial" view, because the Java language does not require methods to catch or specify runtime exceptions, it is attractive for programmers to write code that only throws runtime exceptions or make all their abnormal subclasses inherit from runtimeException. These programming shortcuts allow programmers to write java code without being disturbed by all critical errors from the compiler, and without specifying or catching any exceptions. Although this may seem convenient for programmers, it avoids Java's intent to capture or specify requirements, and can cause problems for programmers who use the classes you provide.

The checking exception represents useful information about a legally specified requested operation. The caller may have no control over the operation, and the caller needs to be notified -- for example, the file system is full, or the remote connection has been closed, or the access rights do not allow the action.

翻译错误 TIMEOUT

In other words, sun tells us that checking for exceptions should be the rule. The tutorial continues in a number of ways, usually throwing an exception rather than a runtimeException -- unless you are a JVM.

In the effective Java: Programming Language Guide (see resources), Josh Bloch provides the following knowledge points about checked and non checked exceptions, which are consistent with (but not strictly consistent with) the recommendations in "the java tutorial":

Article 39: use exceptions only for exceptional conditions. That is, do not use exceptions for control flow, for example, when calling iterator Next() instead of checking the iterator for the first time NoSuchElementException caught when hasnext().

Article 40: use check exceptions for recoverable conditions and run-time exceptions for programming errors. Here, Bloch responds to the traditional sun view that runtime exceptions should only be used to indicate programming errors, such as violation of preconditions.

Article 41: avoid unnecessary use of inspection type exceptions. In other words, do not use checked exceptions in cases where the caller cannot recover from it, or the only predictable response will be program exit.

Article 43: throw exceptions appropriate to the abstraction. In other words, the exception thrown by a method should be defined at an abstract level, which is consistent with what the method does, not necessarily with the underlying implementation details of the method. For example, a method of loading resources from a file, database or JNDI should throw a resourcenotfound exception (usually using exception chain to save the implied cause), rather than the underlying IOException, sqlexception or namingexception.

1、 Overview of exceptions in Java

1.1 Java exception structure

Throwable can be used to represent any class that can be thrown as an exception. Throwable objects derive two types: error and exception. The former is used to represent compile time and system errors, which programmers often don't need to care about; The latter is a basic type that can be thrown and needs the attention of programmers. RuntimeException is a derived class of exception. The differences will be described in the summary of 2.2 and 2.3.

Java exceptions can be divided into checkedexception and uncheckedexception according to the compiler checking method.

1.2 checkedexception

In Java, all exceptions that are not derived from runtimeException are check exceptions. When there is an operation that throws a check exception in a function, the function declaration of the function must contain the throws statement. The function calling the modified function must also handle the exception. If not, the throws statement must be declared on the calling function.

Checked exceptions are first created in Java, and there are mandatory requirements for exception handling at compile time. In JDK code, a large number of exceptions belong to check exceptions, including IOException, sqlexception and so on.

1.3 unchecked exception

In Java, all derived classes of runtimeException are non checking exceptions. Compared with checking exceptions, throwing non checking exceptions does not need to add throws statements in the function declaration, and there is no need to force processing on the calling function.

Common nullpointexception and ClassCastException are common non checking exceptions. Non checking exceptions can not use try Catch, but if an exception is generated, the exception will be handled by the JVM. For subclasses of runtimeException, it is better to use exception handling mechanism as well. Although the exception of runtimeException can not use try Catch is used for processing, but if an exception occurs, it will certainly interrupt the execution of the program. Therefore, in order to ensure that the program can still be executed after another error, it is best to use try when developing code Exception handling mechanism of catch.

1.4 keyword of exception

Java exception handling involves five Keywords: try, catch, finally, throw and throws

The related syntax of the five key words.

2、 Exception handling method

2.1 abnormal chain

At jdk1 In versions after 4, the throwable class supports the exception chain mechanism. Throwable contains a snapshot of the thread execution stack when its thread is created. It also contains a message string that gives more information about the error. Finally, it can also include cause: another throwable that causes this throwable to throw. It is also called exception chain facility, because cause itself will have cause, and so on, forming an exception chain. Each exception is caused by another exception.

Generally speaking, the exception chain is to wrap the original exception into a new exception class, and encapsulate the original exception class in the new exception class. The purpose of this is to find the root cause of the exception.

2.2 abnormal translation

Exception translation is the process of converting an exception into another new exception and throwing it again. The purpose of exception translation is to unify the types of different types of exceptions in the system, so as to facilitate the unified handling of exceptions. In most cases, the translated "result exception" type is a user-defined exception, and the "original exception" needs to be placed in the exception chain during the exception translation process.

2.3 custom exception

Custom exceptions are self written exception classes that inherit exception or runtimeException. The purpose of realizing custom exceptions can be roughly divided into the following three types:

1. Use a unified type to identify many different types of exceptions.

2. Better information transmission in case of exceptions. The common method is to define the exception code, exception information, environment object and other fields in the exception.

3. Convert checked exceptions to non checked exceptions.

III. exception handling

3.1 debate on inspection type anomaly and non inspection type anomaly

In the actual programming process, the time to use checked and non checked exceptions has been produced since the day when the Java language was produced.

For the most official statement, please refer to the chapter on the use of exceptions in effective Java by Joshua block, one of the core designers of Java. His proposition is to use check exceptions for recoverable situations and run-time exceptions for programming errors.

Although the above statement has "royal blood", in fact, in my opinion, Java's check exception is a very failed work, because the check exception has strong "pollution", and its emergence brings much more trouble than benefits. My view is that checking exceptions should not be used in almost all cases. When a checked exception cannot be handled, you should use exception translation to convert it to a non checked exception and throw it again. I am very excited to see that the author has described this view in detail on think in Java 4th Edition.

The original intention of Java to create checked exceptions is to force programmers to deal with exceptions during compilation, so as to make the program more robust and reliable. However, the author of Java has forgotten that a good programming language can help programmers write good programs, but no matter which language, programmers can't avoid using it to write bad programs.

The key point of exception handling is not whether to check exceptions during compilation or run time, but that exceptions must be checked and a unified and consistent exception checking and handling model needs to be established.

3.2 my exception handling principles

1. Process only the currently treatable exceptions.

2. Use exception translation for all inspection exceptions.

3. All custom exceptions are non check exceptions.

4. The abnormal process shall be separated from the normal process and handled as uniformly as possible.

5. Try not to log in the catch block of the non exception handling module.

6. Unless the resource is released, the catch block should not be empty or e.printtrace should appear

7. Complex operations cannot occur in the finally block, and no exception or return can be thrown.

3.3 general ways of handling exceptions

1. Regard the throw statement as the starting point of the exception process and the exception object as the data carrier during the transition from normal process to exception process.

2. Create a unified user-defined exception type to package all inspection exceptions.

3. In most cases, only a unique exception capture point is established on the trunk of the program, and the received exceptions are processed at this point.

summary

The above is the whole content of this article. I hope it will be helpful to you.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>