Java programmers must: Abnormal ten key knowledge points

Foreword

Summarizes the Java exception Ten Key knowledge points, interview or work there with, oh, come on.

A. What is abnormal

An anomaly is a problem to stop the current method of execution or scope continues . For example, you read the file does not exist, array bounds, when division, division by zero, and this will result in an exception.

A file not found exception :

public class TestException {
    public static void main(String[] args) throws IOException {
        InputStream is = new FileInputStream("jaywei.txt");
        int b;
        while ((b = is.read()) != -1) {

        }
    }
}
复制代码

operation result:

Exception in thread "main" java.io.FileNotFoundException: jaywei.txt (系统找不到指定的文件。)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:93)
	at exception.TestException.main(TestException.java:10)
复制代码

II. Abnormal hierarchy

Once upon a time, there was the old man, his name Throwable , he had two sons, the eldest son called Error , the second son called Exception .

Error

When expressed compile or system errors, such as virtual machine-related errors, OutOfMemoryError, etc., error can not be handled.

Exception

Code is abnormal, the base types Java programmers are usually concerned with Exception. It is the program itself can handle, which is its difference with the Error.

It can be divided into a RuntimeException (abnormal operation) and CheckedException (may check exception).

Common RuntimeException exception:

- NullPointerException 空指针异常
- ArithmeticException 出现异常的运算条件时,抛出此异常
- IndexOutOfBoundsException 数组索引越界异常
- ClassNotFoundException 找不到类异常
- IllegalArgumentException(非法参数异常)
复制代码

Common Checked Exception exception:

- IOException (操作输入流和输出流时可能出现的异常)
- ClassCastException(类型转换异常类)
复制代码
  • Checked Exception is the compiler requires an exception you have to dispose of.
  • In contrast, Unchecked Exceptions, it refers to the compiler does not require unusual force disposal, and which comprises Error RuntimeException and their subclasses.

Third, the exception handling

When an exception occurs, the exception object is created on the heap. The current execution path is terminated, and a reference to the pop-up from the current exception object environment. This time exception handling program, a program to recover from the error state, the program continues to run down.

Exception handling major exception is thrown, catch the exception, unusual statement. Figure:

Catch the exception

try{
// 程序代码
}catch(Exception e){
//Catch 块
}finaly{
  //无论如何,都会执行的代码块 
}
复制代码

We can try...catch...catch the exception code, and then by finalyperforming the last operation, the closing operation such streams.

Statement thrown

In addition to try...catch...catching exceptions, we can also throw an exception through the throws statement.

When you define a method, you can use throwskeyword statement. Use the throwskeyword indicates that the method does not handle the exception, but the abnormal left to its caller process. TA is not that irresponsible?

Haha, look at the demo it

//该方法通过throws声明了IO异常。
 private void readFile() throws IOException {
        InputStream is = new FileInputStream("jaywei.txt");
        int b;
        while ((b = is.read()) != -1) {

        }
    }
复制代码

Thrown from the method declaration of any exception must use throws clause.

Throw an exception

throw throw a key role is Throwablethe type of anomaly, it usually appears in the function body. In exception handling, try to capture the statement is an exception object, in fact, you can own this exception object thrown.

For example, throw a RuntimeException exception object class:

throw new RuntimeException(e);
复制代码

Any Java code can be thrown by the Java throw statement.

important point

  • Non-abnormalities (Error, RuntimeException, or their subclasses) can not be used throws keyword to declare an exception to be thrown.
  • Abnormal, you need to try-catch / throws a processing method appears to compile, otherwise it will cause a compiler error.

Four, try-catch-finally-return execution sequence

try-catch-finally-return execution described

  • If an exception occurs, will not be part of the implementation of catch.
  • With or without exception, finally will be executed to.
  • Even when there are return try and catch in, finally will still be executed
  • finally it is performed in a later return operation after completion of expression. (At this point the value of the operation and did not return, but the first saved value to be returned, if finally no return, no matter how kind finally the code, the return value will not change, still the previously saved value), the function return value in this case is performed before finally determined)
  • finally part do not return, or else, you can not go back or try the catch of return.

Look at an example

 public static void main(String[] args) throws IOException {
        System.out.println("result:" + test());
    }

    private static int test() {
        int temp = 1;
        try {
            System.out.println("start execute try,temp is:"+temp);
            return ++temp;
        } catch (Exception e) {
            System.out.println("start execute catch temp is: "+temp);
            return ++temp;
        } finally {
            System.out.println("start execute finally,temp is:" + temp);
            ++temp;
        }
    }
复制代码

operation result:

start execute try,temp is:1
start execute finally,temp is:2
result:2
复制代码

analysis

  • Try to perform some of the output log, performed ++tempexpression, TEMP becomes 2, this value is saved.
  • Because there is no abnormality occurs, the catch block is skipped.
  • Finally block is executed, a log output, performed ++tempexpression.
  • 2 try to save the value returned portion.

Fifth, several important ways Java exception class

All methods Mew an exception to the first class, as shown below:

getMessage

Returns the detail message string of this throwable.
复制代码

Throwable getMessage returns the detailMessageattributes, detailMessageto a detailed description of the exception message.

For example, FileNotFoundExceptionwhen an exception occurs, this detailMessagecontains the name of the file not found.

getLocalizedMessage

Creates a localized description of this throwable.Subclasses may override this
method in order to produce alocale-specific message. For subclasses that do not
override thismethod, the default implementation returns the same result
as getMessage()
复制代码

throwable localized description. Subclasses can override this method to generate a message specific locale. For subclasses not override this method, the default implementation returns the same result with getMessage ().

getCause

Returns the cause of this throwable or null if thecause is nonexistent or unknown.
复制代码

Returns the cause of the event can be thrown out, or if the cause is nonexistent or unknown, returns null.

printStackTrace

Prints this throwable and its backtrace to thestandard error stream.

The first line of output contains the result of the toString() method for
this object.Remaining lines represent data previously recorded by the 
method fillInStackTrace(). 
复制代码

This method will stack trace to the standard error stream.

The first line of output, containing the object toString () results of the method. The remaining lines represent data previously () method of recording fillInStackTrace. Examples are as follows:

 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
复制代码

Six custom exception

Custom anomaly usually define a subclass inherits from Exception class.

Why, then, you need custom exception?

  • Abnormal Java provides system can not anticipate all of the errors.
  • Business development, the use of custom exception, the code can make the project more standardized, and easy to manage.

Here is our custom exception class is a simple demo

public class BizException extends Exception {
    //错误信息
    private String message;
    //错误码
    private String errorCode;

    public BizException() {
    }

    public BizException(String message, String errorCode) {
        this.message = message;
        this.errorCode = errorCode;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }
}
复制代码

Run a main square test


public class TestBizException {

    public static void testBizException() throws BizException {
        System.out.println("throwing BizException from testBizException()");
        throw new BizException("100","哥,我错了");
    }

    public static void main(String[] args) {
        try {
            testBizException();
        } catch (BizException e) {
            System.out.println("自己定义的异常");
            e.printStackTrace();
        }
    }
}

复制代码

operation result:

exception.BizException: 100
throwing BizException from testBizException()
自己定义的异常
	at exception.TestBizException.testBizException(TestBizException.java:7)
	at exception.TestBizException.main(TestBizException.java:12)
复制代码

Seven, Java7 new try-with-resources statement

try-with-resources, is a new feature Java7 provided it for automatic resource management.

  • Resources are running out after the program must be closed object.
  • try-with-resources to ensure that every resource will be declared closed end of the statement
  • What kind of an object in order to use it as a resource? As long as the realization of the object java.io.Closeable java.lang.AutoCloseable interface or interfaces are OK.

In the try-with-resourcesprior appearance

try{
    //open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {
    // Exception handling like FileNotFoundException, IOException etc
}finally{
    // close resources
}
复制代码

Java7, try-with-resourcesafter the emergence of the use of resources to achieve

try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
    // exception handling
}
// resources are closed as soon as try-catch block is executed.
复制代码

Java7 use of resources demo

public class Java7TryResourceTest {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader(
                "C:/jaywei.txt"))) {
            System.out.println(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
复制代码

Use the try-with-resourcesbenefits

  • Code is more elegant, less the number of rows.
  • Automatic resource management, do not worry about memory leaks.

Eight, abnormal chain

We often want to catch an exception thrown after another exception, and you want to preserve the original exception information, which is called the exception chain .

throwIt throws a new exception information, which can cause abnormal original information is lost. In JDk1.4 before, the programmer must write your own code to save the original exception information. Now all Throwablesubclass constructor can accept an cause(异常因由)object as a parameter.

This causewill be used to represent the original exception, so by the original exception is passed to the new exception, so that even if the current location to create and throw a new exception, but also through the exception chain track the location of the first occurrence of an exception.

Used as follows:

public class TestChainException {

    public void readFile() throws MyException{
        try {
            InputStream is = new FileInputStream("jay.txt");
            Scanner in = new Scanner(is);
            while (in.hasNext()) {
                System.out.println(in.next());
            }
        } catch (FileNotFoundException e) {
            //e 保存异常信息
            throw new MyException("文件在哪里呢", e);
        }
    }

    public void invokeReadFile() throws MyException{
        try {
            readFile();
        } catch (MyException e) {
            //e 保存异常信息
            throw new MyException("文件找不到", e);
        }
    }

    public static void main(String[] args) {
        TestChainException t = new TestChainException();
        try {
            t.invokeReadFile();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

}

//MyException 构造器
public MyException(String message, Throwable cause) {
        super(message, cause);
    }
复制代码

operation result:

We can see that there are anomalies preserved, if the cause (that is, the FileNotFoundException e) get rid of it, look at the results:

Can be found less Throwable cause, the original exception information was missing.

Nine, abnormal match

When thrown, the exception handling system will find the "nearest" handlers in the writing order code. After finding the matching processing program, it is believed an exception would be addressed, then look no further.

When looking for does not require an exception handler throws the same exception exact match. The object of a derived class can also be equipped handler base class which

Nursing demo

package exceptions;
//: exceptions/Human.java
// Catching exception hierarchies.

class Annoyance extends Exception {}
class Sneeze extends Annoyance {}

public class Human {
  public static void main(String[] args) {
    // Catch the exact type:
    try {
      throw new Sneeze();
    } catch(Sneeze s) {
      System.out.println("Caught Sneeze");
    } catch(Annoyance a) {
      System.out.println("Caught Annoyance");
    }
    // Catch the base type:
    try {
      throw new Sneeze();
    } catch(Annoyance a) {
      System.out.println("Caught Annoyance");
    }
  }
}
复制代码

operation result:

catch (Annoyance a) captures Annoyance and all anomalies derived from it. Abnormal capture the base class, you can match all the anomalies derived class

try {
      throw new Sneeze();
    } catch(Annoyance a) {
    } catch(Sneeze s) { //这句编译器会报错,因为异常已由前面catch子句处理
    }
复制代码

Ten, Java common exceptions

NullPointerException

Null pointer exception, the most common of an exception class. In short, call uninitialized object or the object does not exist, it will generate the exception.

ArithmeticException

Arithmetic exception class, the program appears in the divisor is 0 such operations, there will be such an exception.

ClassCastException

Casts exception, the JVM which abnormality is detected when running initiator is not compatible with the conversion between the two types.

ArrayIndexOutOfBoundsException

Array subscript bounds exception, when dealing with an array, you need to pay attention to this anomaly.

FileNotFoundException

File not found abnormal, usually to read or write a file can not be found, leading to the exception.

SQLException

Abnormal operation of the database, which is Checked Exception (abnormalities);

IOException

IO exception, usually closely linked with the read and write files, it is also Checked Exception (abnormalities). Usually read and write files, remember IO streams closed!

NoSuchMethodException

The method not found abnormalities

NumberFormatException

Abnormal string converted to digital

to sum up

This summary inventive, with a few classic face questions abnormal end of it, to help you brush up, hee hee.

  • java, which has several abnormalities, characterized by what? (Knowledge point two can answer)
  • What is Java Exception? (A knowledge can answer)
  • error and exception What is the difference? (Knowledge point two can answer)
  • What is unusual chain? (2.8 knowledge can answer)
  • try-catch-finally-return order of execution (forty knowledge can answer)
  • Lists several common RunException (knowledge point two can answer)
  • What is important is the method of Java exception class? (2.5 knowledge can answer)
  • The difference between error and exception, CheckedException, the difference of RuntimeException. (Knowledge point two can answer)
  • Please list the runtime exception 5. (Knowledge point two can answer)
  • Java 7 new try-with-resources statement (100.7 knowledge can answer)
  • How custom exception? (2.6 knowledge can answer)
  • And talk about common causes of abnormal (ten knowledge can answer)
  • Talk about abnormal matches (100.9 knowledge can answer)
  • Talk about exception handling (thirty knowledge can answer)

Personal Public Number

  • If you are a love of learning boy, I can focus on the public number, learning together discussion.
  • What if you feel that this article is not the right place, can comment, I can also concerned about the number of public, private chat me, we will study together progress Kazakhstan.

Guess you like

Origin juejin.im/post/5dc68c0f51882528957fadb3