java-error handling mechanism learning (a) exception handling

Source: Internet
Author: User

The idea of exception handling is that, when an application is in an exception, it can declare the exception, and then the exception is caught and handled properly to avoid serious consequences. The so-called exception, is the value and the normal running logic of the program is a non-normal event, for example, when reading the contents of the file, the file does not exist, or an array of operations, arrays subscript out of bounds and so on. Password validation fails at user logon This situation cannot be counted as an exception because it is part of the logic that validates the normal operation of the thread.

First, the abnormal hierarchy structure and classification

The exception hierarchy in Java is as follows:

The error class hierarchy describes internal errors and resource exhaustion errors for the Java Runtime system. The application is powerless for this kind of error, so applications should not throw objects of this type.

The exception hierarchy is decomposed into two branches: one is derived from RuntimeException, which represents an exception caused by a program error. such as null pointers, array out-of-bounds, wrong type conversions, and so on.

Another branch shows that the program itself is not a problem, the problem is the IO read and write external operations, such as reading data at the end of the file, open the wrong URL, and so on.

The Java language Specification will derive all exceptions for the dry error class or RuntimeException class called an unchecked (unchecked) exception, and all other exceptions are referred to as checked (checked) exceptions. The compiler provides an exception handler for all of the checked exceptions.

Second, the declaration has checked the exception

According to the exception specification, the method should declare all possible exceptions at the header. However, the unchecked anomaly is either uncontrollable (Error) or should be avoided (runtimeexception). Therefore, the prescribed method must declare any checked exceptions that may be thrown, otherwise it cannot be compiled.

So how do we know if a method actually has checked exceptions? Don't worry, the compiler will be able to prompt us. When a method invokes a method that might throw an exception, Eclipse automatically alarms, such as:

 

If you do not follow the prompts for modification, the program cannot compile.

C. Throw an exception

Suppose the application now encounters an error and needs to throw an exception to alarm. So, the first thing to determine is the type of exception. Java has already defined many exception, common ioexception/sqlexception and so on, and more types can be identified by the lookup API. Of course, we can also inherit exception and create our own exceptions. Next, create an exception instance and throw an exception using the Throw keyword. Finally, declare the exception type that is thrown in the method signature. The sample code is as follows:

 Public void throws exception{        if(!  File.exists ()) {            new  filenotfoundexception ();             Throw e;        }    }

Iv. Catching exceptions

The exception is captured and processed in the following format:

 Public voidCallread () {Try {            //code that could throw an exceptionReadNewFile ("filename1")); Read (NewFile ("Filename2")); } Catch(Exception e) {//Exception handling CodeE.printstacktrace (); }        finally{            //code that needs to be executed anyway, such as freeing resources        }    }

where try{}catch{} is required, finally is optional. The code that may throw the exception must be placed in try{}, otherwise the exception cannot be caught, and when the exception is caught, jump directly to catch{} for exception handling. For example, if you catch an exception while reading filename1, then read (New File ("filename2")), and the code will be skipped and no longer executed.

There are usually more than one exception, and it is not recommended to use the exception object for capture because it is too generic to reflect the specific type of exception. The correct approach is to treat different exceptions separately, i.e. overlay multiple catch blocks.

There are always some work in the program, such as releasing resources, regardless of whether the exception or not need to do, it can be placed in finally{}, it will be executed after the completion of catch{}. Even if there is a return statement, it will not return until the end of finally{}.

V. Throw an exception again

java-error handling mechanism learning (a) 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.