Java and most complete anomaly to explain

1. The guiding question

The actual work situation encountered can not be perfect. For example: You write a module, the user input may not meet your requirements, your application to open a file, the file may not exist or the file format is wrong, you have to read the data in the database, the data may be empty Wait. We ran the program again, memory or hard disk may be full. and many more.

Software program during operation, is very likely to experience these unusual problems just mentioned, we call abnormal, English is: Exception, which means an exception. These exceptions, or called abnormal, how we write the program to make a reasonable deal. The program will not crash.

1.1 common errors:

    User input error

    Device error. Hardware problems, such as turn off the printer, server problems

    Physical limitations. Disk full

    Code restrictions. Array subscript out of bounds, etc.

A well-designed program should provide a method for processing these errors when an abnormality occurs, so that the program will not end because of the occurrence of abnormality or broken produce unpredictable results.

If no exception handling mechanism, then:

1.2 two disadvantages:

1. Logic code and error handling code put together!

2. Exceptions programmer itself be considered a complicated process, the programmer itself requires!

The exception mechanism occurs when the program is wrong, the program how to safely exit mechanism.

2. The concept abnormal (Exception) of

How Java handle exceptions?

And parsing the first exception example:

public static void main(String[]args){
    int i=1/0;
Exception in thread"main"java.lang.ArithmeticException:/by zero at chuji.BubbleSort.main(

Java is an object-oriented approach to handle exceptions.

3. processing

Throws an exception: in the implementation of a method, if an exception occurs, this method generates an object representing the anomaly, stop the current execution path, and the exception object submitted to the JRE.

Capture exception: the exception is obtained after JRE, find the appropriate code to handle the exception. JRE look at the call stack method, starting from the method generates an exception back until you find the appropriate exception handling code so far.

4. malfunction classification

JDK defines many exception classes, these classes correspond to a wide variety of unusual events that may occur, all the exception object is an instance of Throwable derived class. If the built-in exception classes can not meet your needs, you can also create your own exception classes.

The relationship between the anomaly category

Figure references link: https: //

4.2 Error

Error class hierarchy describes internal errors and resource exhaustion system Java runtime error. Such errors are beyond our control, but also very rare error. So in programming, we do not deal with this type of error.

JVM Error indicates that the system is already in a state of collapse unrecoverable. We do not need to control him.

Open the JDK: java.lang.error, to see all of his subclasses.

4.3 Exception

Superclass of all exception classes, subclasses correspond to the wide variety of unusual events that may occur.

4.4 Error and Exception of difference

I drove down the road a pig in the middle of the road red, I brake. This is called an exception.

I was driving a car on the road, the engine is broken, I stop, called error. The system is in a state of collapse unrecoverable. When the engine bad? We ordinary drivers to control it? Can not. When the engine is bad carmakers engine plant matter.

4.4.1 Runtime Exception

RuntimeException occurs it must be your problem, you can not capture, be careful because these anomalies can be avoided. Derived from RuntimeException exception. Is a special kind of abnormality, such as by 0, the array subscripts of range, etc., which generates more frequent, troublesome process, if the statement or an explicit program will capture the readability and operation efficiency greatly. Thus automatically detected by the system and to their default exception handler (user does not have to handle them). Such exceptions are usually caused by programming errors, because only careful, these abnormalities can be avoided, so the preparation process is not required to use exception handling mechanism to deal with such exceptions, all of these abnormalities are inherited since java.lang.RuntimeException.

Common runtime exceptions are:

  1. ArithmeticException

    Any attempt to divide by zero

  2. NullPointerException

    Occurs when a program accessing a null object member variables or methods, an empty array of member access

  3. ClassCastException

    After polymorphism occurs, force conversion occurs when a subclass is not the parent class. Compile time can pass, because the problem does not compile time checking of type conversion

  4. ArrayIndexOutOfBoundsException

    Element exceeds the length of the array access table

  5. NumberFormatException

    Abnormal digital format!


We usually encounter NullPointerException, which is a null pointer of the problem, do not just remember Baidu, from where the error should be to analyze your own code, because the null pointer actually write your code is not strict caused. Null pointer Solution: Debug, you see the corresponding value is null.

4.4.2 Checked Exception

All is not Runtime Exception exception, collectively referred to as Checked Exception, also known as “checked exceptions.” Such a problem is not the program itself unusual, usually caused by external factors. In order to prevent these anomalies generated when the cause of the interrupt program or get incorrect results, Java program code required to write such exceptions may occur, be sure to do exception handling.

The compiler will check for exception handling for all checked exceptions.

This type of anomaly, we must capture processing.

Java language class will send born RuntimeException or Error class all the exceptions referred to as “unchecked exceptions.”

5. One unusual approach: catch the exception

5.1 try

try statement specifies a code, which is a segment of code capture and processing range. During execution, when a statement is any abnormality occurs, it skips the following block code. The code may generate an exception object and throw one or several types of catch statement behind it to each of these abnormalities corresponding processing

A try statement must have at least one catch block or a finally block.

Note: When the end of the implementation of the code exception handling, the statement will not return to try to execute the code has not been executed.

5.2 catch

1, each try block may be accompanied by one or more catch statement for exception handling of different types of objects may be generated.

2, commonly used methods:

toString () method, the class name and the reason display abnormal abnormality
    getMessage () method, only the abnormality cause, but does not display the name of the class.
    printStackTrace () method, used to track the contents of the stack when an abnormal event occurs.

These methods are inherited from the Throwable class

3, catch capture capture sequence when an abnormality:

If an exception inheritance relationship between classes, on the order of arrangement should pay attention to. The more level class (parent class), the more on the following. Or else directly to the excess catch omitted.

5.3 finally

Some statements, regardless of whether there has been an exception, must be performed, then you can put this statement into finally block.

Block is normally closed in the finally open resources, such as: file stream, release the database connections.

5.4 typical code

public class TestException {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
            reader = new FileReader("d:/a.txt");
            char temp = (char);
            System.out.println("读出的内容:" + temp);
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        } finally {
            System.out.println(" 不管有没有异常,我肯定会被执行!");
            try {
            } catch (IOException e) {

5.5 try, catch, finally, return the execution order

The order of execution:

1. Implementation of try, catch, return value to assign

2. Finally executed


6. unusual approach II: unusual statement (throws clause)

When Checked Exception produce, not necessarily immediately deal with it, you can then abnormal Throws out.

This method uses the processing exception try-catch-finally in the process. In some cases, this method does not require the processing of the exception, but passed up to the calling process method.

If a method might produce some kind of anomaly, but it does not determine how to deal with this anomaly, an exception should be based specification exception in the header declarations of methods which might be thrown.

If a method throws more checked exceptions, it must list all the exceptions in the first part of the method, among separated by commas.

6.1 typical code

public class FileTest {
    public static void main(String[] args) {
        try {
        } catch (FileNotFoundException e) {
        } catch (IOException e) {

    public static void readFile(String fileName) throws IOException {
        FileReader in = new FileReader(fileName);
        try {
            int tem = 0;
            tem =;
            while (tem != -1) {
                System.out.println((char) tem);
                tem =;
        } finally {

6.2 Method in exception principle declared rewrite

Abnormal range subclass declaration can not exceed the scope of the parent class declaration. It includes the following meanings:

    The parent class does not declare an exception, not the subclass;

    Not throw the original method throws an exception parent class or upper class category

    The number of types of exceptions may not be thrown further than the original multi-thrown (not refers to the number)

7. The three unusual approach of: Hand throw an exception (throw clause)

Java exception class object is automatically generated except when an exception occurs during the execution of the program by the system and throw, you can create and throw manually if desired.

Before capturing an exception, there must be a period of Mr. code into the exception object and throw it. We can do this process manually, can also be achieved by the JRE, but they are calling throw clause.

For an existing exception class, the class of the exception object is thrown as follows:

  1. Find an appropriate exception class.

  2. Create objects of that class.

  3. The object Throws

File f=new File("c:/tt.txt");
        throw new FileNotFoundException("File can't be found!");
    }catch(FileNotFoundException e){

8. custom exception

In the program, you may experience any of the standard exception classes are not sufficiently clear description of the problem, you can create your own exception class in this case.

How to do it:

A subclass derived from the Exception class or subclass to its

Traditionally, the class definition should contain two constructors: a default constructor, a constructor with other details.

Typical code

class IllegalAgeException extends Exception {
    public IllegalAgeException() {

    public IllegalAgeException(String msg) {

class Person {
    private String name;
    private int age;

    public void setName(String name) { = name;

    public void setAge(int age) {
        if (age < 0) throw new IllegalAgeException("人的年龄不应该为负数");
        this.age = age;

    public String toString() {
        return "name is " + name + " and age is " + age;

public class MyExceptionTest {
    public static void main(String[] args) {
        Person p = new Person();
        try {
        } catch (IllegalAgeException e) {

9. Use exception mechanism recommended

    To avoid the use of exception processing instead of the processing error, this will reduce the clarity of the program, and inefficient (Java is an object-oriented way to handle exceptions, so there is some overhead)

    Use exceptions only in exceptional circumstances mechanism

    Exception handling small size --- Do not make the whole task should as far as possible packed in a Try statement block

    Abnormal often thrown in the lower, upper layer processing (capture)

10. summary

    A map

    Five keywords (try, catch, finally, throws, throw)

    First catch small (sub-class), and then catch large (parent)

    Relationship between abnormal and rewriting

    Custom exception

Like now, in fact, it is not really like it, just do not understand it because, true love, is based on very understanding. Learn java-based, like programming, no longer confused.

Like the article, then we can focus on scanning micro-channel public number

Search micro-channel public number: Java know why, can receive a free lesson, by the end face after Java and other resources, as well as a unified environment (teach you how to configure a development environment) video collection.

Leave a Reply