I used to be a happy iOS developer and kept seeing a picture:





An exception is thrown

Crash, crash, crash, crash, crash, crash. Later, after my study of JAVA I found that my thoughts were slap slap face, it is called a left and right open. ( ̄ε(# ̄)☆╰╮( ̄▽ ///) or I am too naive, and today, is going to detail the abnormal things.


We need to establish a concept of what an exception mechanism is.

The exception mechanism refers to how the program handles errors when they occur. Specifically, the exception mechanism provides a safe path for a program to exit. When an error occurs, the flow that the program executes changes, and control of the program passes to the exception handler.

Once you understand how the exception mechanism works, the exception handling process is easy to follow.

After throw an exception when the program, the program from the program leads to abnormal jump out of the code, the Java virtual machine can search and the try keyword matching process the abnormal catch block, if found, will make the catch block control code, and then continue to execute a program, an exception occurs in the try block code will not be rerun. If no catch block is found to handle the exception, the current thread that encountered the exception is aborted after all finally block code is executed and the uncaughtException method of the ThreadGroup to which the current thread belongs is called.

In code:

        try {
            System.out.println("Find the try keyword");
        } catch (Exception e){
            e.printStackTrace();
            System.out.println("Catch exception");
        } finally {
            System.out.println("The code in finally will be executed whether it goes try or catch.");
        }Copy the code

java.lang.Throwable

Java.lang.Throwable is the superclass for all errors or exceptions in Java. An object can only be thrown by a JVM or Java throw if it is an instance of this class (or one of its subclasses). In other words, all exceptions come from it, and it is the parent class of all exceptions. And, similarly, only this class or one of its subclasses can be a parameter type in a catch clause.





Relationships between common exceptions

As you can see, it has two subclasses that distinguish between two different types of exceptions.


The first kind. Java. Lang. Error

Error is a subclass of Throwable and is used to indicate a serious problem that a reasonable application should not attempt to catch. How serious is this problem? A very serious, unrecoverable Error, in which case the program must terminate. However, it is important to note that the compiler does not check to see if Error is handled, and programs do not catch errors of this type. In general, programs should never throw such exceptions. However, the source code must be modified once an Error occurs.

Java.lang.exception

Exceptions are exceptions that are issued by the JVM. There are two types of exceptions: RuntimeException and Checked Exception or (memorized) non-RuntimeException.

The RuntimeException type is an Unchecked Exception. The compiler does not check whether programs are handling runtimeExceptions, nor does it catch exceptions of the RuntimeException type in programs. RuntimeException is not thrown in the method body. RuntimeException indicates a logical programming error in the program. The programmer should find the error and fix it.

Checked Exception, or non-RuntimeException, is Exception except for RuntimeException, JAVA requires all Checked exceptions to be handled, and the compiler checks to see if they exist, and either throws them, or tries to catch them, or it fails to compile.


What to do if an exception occurs?

For exception, really useful is the object type of intention, not the exception object itself, each kind of exception object has its own meaning, old rules, for easy to understand, on the code!

    public static double div(int a, int b){
        return a / b;
    }
    // Then call
    div(4.0);Copy the code

Obviously, we made a very basic mistake, which was to take an integer and divide it by 0, of course, our dear JAVA doesn’t spoil us.





Throw an exception

Let’s look at the exception message thrown.





Exception information

We’re going to see a couple of interesting things here.

  1. Java. Lang. ArithmeticException this thing seems to be the class?
  2. By zero, I think I just divided by zero.
  3. At com.any.main. div(main.java :69) at com.any.main. Main (main.java :28)

We first take a look at the Java. Lang. ArithmeticException, the meaning of this class is when abnormal operation conditions, throw this exception. As we did, an integer “divided by zero” throws an instance of this class.

And then by zero, it’s really divided by zero, it’s fine.

And finally, the last two lines, div and main seem to be your two methods, is main the main entry? You look at lines 69 and 28

   return a/b;/ / 69 rows
   div(4.0);/ / 28 linesCopy the code

Exclaim magic. Now you can understand anomalies.


Custom exception

You think knowing the anomaly is the end of it? Programming changes so fast. How can you be sure that JAVA takes into account all the things you can go wrong? Therefore, when JAVA built-in exceptions do not clearly describe the exception, you need to create your own exception. Note, however, that the only useful information is the type name, so don’t bother with the design of the exception class, it’s just there to give you information. Or on the code to clear, please see.

class Computer {
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) throws DownException.EnterWaterException {
        this.status = status;
        if (status.equals("Water")) {throw new EnterWaterException("It's flooded and burned.");
        } else if (status.equals("Fell")) {throw new DownException("I fell. I got money."); }}private  String status;
}

class DownException extends RuntimeException{
    public DownException(String message){
        super(message); }}class EnterWaterException extends RuntimeException{
    public EnterWaterException(String message){
        super(message); }}Copy the code

You can clearly see that I created two new exceptions, put them in a class called Computer, and told the setStatus method to throw them up.

        Computer computer = new Computer();
        try {
            computer.setStatus("Water");
        } catch (EnterWaterException e){
            e.printStackTrace();
        } catch (DownException e){
            e.printStackTrace();
        } finally {
            System.out.println("finally");
        }Copy the code

And then I try catch the exception. Take a look at the output.





Exception information

Well, it’s not obvious, but there are a few things to note here, and keep in mind.

  1. As to whether we should throw exceptions in declared methods or catch them in methods, we should follow the principle of catching and handling the exceptions we know how to handle and passing the exceptions we don’t know how to handle
  2. Multiple exception capture, exception objects exist parent-child relationship is required, the parent type of the exception, written below the subclass
  3. Multiple exceptions can be combined in a single catch catch(Exception e), but I didn’t do that for clarity.
  4. Throws declares that there is an exception in the call of this method, and the caller needs to capture or continue throwing to pass compilation
  5. When something goes wrong with the code, the JVM creates an exception object and throws the caller
  6. The caller receives an exception and cannot handle it, continues to throw it up to the JVM, and finally outputs the exception information to the console




Finally, output to the console


Here are some common exceptions to compare with when you throw them:

ArithmeticException — the exception caused by a divisor of 0; ArrayStoreException – Exception caused by insufficient array storage space; ClassCastException – an exception is raised when an object is classified as a class that was not actually created by that class or a subclass of that class; IllegalMonitorStateException – monitor state error caused by abnormal; NegativeArraySizeException – an array length is negative, will produce abnormal; NullPointerException – an exception raised when a program attempts to access an element in an empty array or access a method or variable in an empty object; OutofMemoryException — an exception occurs when an object is created with a new statement if the system cannot allocate memory space for it; SecurityException – an exception caused by a security problem by accessing a pointer that should not be accessed; IndexOutOfBoundsExcention – caused by array subscript bounds or string access cross-border exception; IOException — an exception caused by a file not found, not opened, or an I/O operation cannot take place; ClassNotFoundException — No class or interface with the specified name was found causing an exception; CloneNotSupportedException – a program of an Object reference Object class clone method, but this Object is not connected to the Cloneable interface, causing abnormal; InterruptedException – When one thread is in a waiting state, another thread interrupts the thread, causing an exception; NoSuchMethodException a method called was not found, causing an exception; Illega1AccessExcePtion – an attempt to access a non-public method; StringIndexOutOfBoundsException – access string number of crossing the line, cause abnormal; ArrayIdexOutOfBoundsException – a visit to array element subscript bounds, cause abnormal; NumberFormatException — Error in the UTF code data format of a character causes an exception; IllegalThreadException – a thread that calls a method in an inappropriate state causes an exception; FileNotFoundException — failed to find specified file causing exception; EOFException – An exception is caused when an input operation is not completed.


How about, everyone has their own understanding of the anomaly, I hope you want to reach the level of the picture below.





Solve abnormal

As programmers, we just want to every day is to me how to knock the code more cow force, more beautiful, and I always thought that the knowledge, insight and experience sharing and learning is an important way of self study, so, knowledge sharing appreciation, always look forward to working with you very much in crossing play idea, exchange experience.

Other personal articles: Details of JAVA constructors and code blocks themselves and their execution StringBuilder provides JAVA ArrayList and LinkedList for StringBuilder development Notes