Java Exception Handling

Source: Internet
Author: User
Tags finally block

Exceptions include compile exceptions and run-time exceptions, while compile-time exceptions are mainly our syntax exceptions, and run-time exceptions are primarily exceptions that occur during code runtime.

Exceptions are handled as objects in Java, the root class is the Java.lang.Throwable class, and many exception classes are defined in Java (such as OutOfMemoryError, NullPointerException, Indexoutofboundsexception, etc.), these exception classes fall into two main categories: Error and exception.

Error is a problem that cannot be handled, and is an issue that we usually cannot solve with code.

Exception, which is something we often see, such as NullPointerException, indexoutofboundsexception, are exceptions that we can handle.

Exceptions to the exception class include checked exception and unchecked exception (unchecked exception also known as Run-time exception runtimeexception, Of course, the run-time exception here is not the exception that I described earlier in the run, but the term "runtime exception" is used in Java to indicate that the exception of the exception class occurs during runtime.

Unchecked Exception (non-check exception), also known as Run-time exceptions (runtimeexception), such as Common NullPointerException, indexoutofboundsexception. For run-time exceptions, the Java compiler does not require exception capture processing or claims to be thrown, which is the programmer's discretion.

Checked exception (check for exceptions), also known as non-runtime exceptions (exceptions other than runtime exceptions are non-runtime exceptions), the Java compiler forces programmers to have capture processing, such as common Ioexeption and SqlException. For non-run-time exceptions, compilation does not pass without capturing or throwing claims processing.

In Java, the structure hierarchy of the exception class is shown in the diagram:

In Java, the parent class of all exception classes is the Throwable class, the error class is the parent of the error type exception, the exception class is the parent class of the exception type exception, and the RuntimeException class is the parent of all runtime exceptions. Classes other than RuntimeException and inheriting exception are non-runtime exceptions.

Typical runtimeexception include NullPointerException, indexoutofboundsexception, IllegalArgumentException and so on.

Typical non-runtimeexception include IOException, SqlException and so on.

Handling Exceptions:

, Java can choose three methods for exception handling:

1) to code block with try: Catch for exception capture processing;

2) in the code of the method body external throws to throw the declaration, tell the caller of this method this code may appear these exceptions, you need to handle carefully. There are two scenarios:

If a declaration throws an exception that is a non-runtime exception, the caller of this method must be displayed with try: Catch block or continue to throw an exception to the upper layer.

If a declaration throws an exception that is a run-time exception, the caller of this method can selectively perform exception-trapping processing.

3) throws an exception object in the code block with a throw, and there are two cases, similar to 2, in this case:

If the exception object that is thrown is a non-runtime exception, the caller of this method must be displayed with try: Catch block or continue to throw an exception to the upper layer.

If the exception object that is thrown is a run-time exception, the caller of this method can selectively perform exception capture processing.

(If the exception is eventually thrown to the main method, it is equivalent to handing the JVM automatic processing, at which point the JVM simply prints the exception information)

Three. Deep understanding of Try,catch,finally,throws,throw Five keywords

Let's take a look at the usage of the five keywords in the anomaly mechanism and the areas to be aware of.

1.try,catch,finally

The Try keyword is used to enclose logical code that may appear to be abnormal, which is not used alone and must be used with catch or finally. The Java compiler allows a combination of the following three forms:

Try...catch ...;    Try....finally ...; Try....catch...finally ...

Of course the catch block can have multiple, note that the try block has only one, and the finally block is optional (but there can be at most one finally block).

Three blocks are executed in the order of try->catch->finally.

Of course, if no exception occurs, the catch block will not execute. However, the finally block is executed under any circumstances (it is very important to note that, in some cases, the action to dispose of the resource is placed in the finally block).

When there are multiple catch blocks, they are matched in the order of the catch blocks, and once the exception type is matched by a catch block, it does not match the catch block that follows.

When using try: Catch.. Finally block, be careful not to use return in the finally block, because return in finally overwrites the existing return value.

2.throws and Thow Keywords

1) throws appears in the declaration of the method, indicating that the method may throw an exception, and then to the upper layer called its Method program processing, allowing throws followed by a number of exception types;

2) It is generally used when a programmer has some kind of logic to throw a particular type of exception. The throw will only appear in the method body, and when the method encounters an exception during execution, the exception information is encapsulated as an exception object and then thrown out. A very important function of the throw keyword is the conversion of the exception type (which is explained later).

Throws represents the possibility of an exception, which does not necessarily occur; throw throws an exception, and the throw throws a certain exception object. Both are negative ways of dealing with exceptions (the negativity here is not to say that this is not a good way), just throw or maybe throw exceptions, but not by methods to handle exceptions, real handling exceptions are handled by the upper call of this method.

Four. When the class inherits, how to make the exception throw declaration when the method overrides

This section discusses how to determine the type of exception-throwing declaration when a subclass overrides a parent class method. Here is the three-point principle:

1) The method of the parent class does not declare an exception, and the subclass cannot declare the exception when overriding the method;

2) If a method of the parent class declares an exception exception1, the exception declared by the subclass when overriding the method cannot be the parent class of Exception1;

3) If a method of a parent class declares an exception type that has only a non-runtime exception (run-time exception), the subclass declares an exception when overriding the method (runtime exception) and cannot contain a run-time exception (non-runtime exception).

Five. Several recommendations for exception handling and design

Here are some suggestions for exception handling as summarized by predecessors:

1. Use exceptions only where it is necessary to use exceptions, and do not use exceptions to control procedures

Using exceptions with caution, the cost of exception trapping is very high, and excessive use of the exception can severely affect the performance of the program. If you can use the IF statement and the Boolean variable in the program to make logical judgments, then minimize the use of the exception, so as to avoid unnecessary exception capture and processing.

2. Avoid using empty catch blocks

Doing nothing after catching an exception is the equivalent of ignoring the exception. Do not use empty catch blocks, empty catch blocks mean that you hide errors and exceptions in your program and are likely to result in an uncontrolled execution of your program. If you are very sure that the caught exception does not affect the program in any way, it is best to log the exception in log logs for easy updating and maintenance later.

3. Check the selection of exceptions and non-check exceptions

Once you decide to throw an exception, you will have to decide what exception to throw. The main problem here is whether to throw a check exception or a non-check exception.

Checking for exceptions leads to too much try...catch code, and there may be a lot of check exceptions that are not reasonably handled by developers, such as SqlException, and developers have to go try...catch, This leads to a situation where there are only a few lines of logical code, and there are many lines of code for exception capture and processing. This not only makes the logic code read obscure, but also reduces the performance of the program.

I personally recommend to avoid checking the use of exceptions, if it is true that the occurrence of the exception is very common, you need to remind the caller to handle the case, use a check exception, otherwise use a non-check exception.

Therefore, in general, I feel as far as possible to turn the inspection anomaly into a non-check exception to the upper processing.

4. Note The order of catch blocks

Do not put the exception of the upper class in the first catch block. Subclass exceptions should be placed on the parent exception, or it will never be caught,

5. Do not put the information provided to the user in the exception information

6. Avoid recording the same exception in log messages multiple times

Log information is logged only where the exception first occurs. In many cases the exception is layered upward, and if it is thrown up each time, log to the log system, it will not find the root cause of the exception occurred.

7. Exception handling as far as possible at the high-level

As far as possible, the exception is thrown to the upper-level caller, which is handled when the upper-level caller is unified. If it is handled directly in each occurrence of an exception, it can cause confusion in the program exception handling process, which is detrimental to post maintenance and exception troubleshooting. Processing by the upper layer will make the process of the whole program clear and understandable.

8. Releasing Resources in finally

If you are using file reads, network operations, and database operations, remember to release resources in finally. This not only causes the program to consume less resources, but also avoids unnecessary anomalies that occur due to resources not being released.

Article from Http://www.cnblogs.com/zhongyang9898/p/5774725.html's blog. Easy to find.

Java Exception Handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.