Exception Error in Java and the similarities and differences

Error (error) and Exception (abnormal) is a subclass of java.lang.Throwable class in Java code only inherit Throwable instance of the class in order to be throw or catch.

Exception and Error reflects the Java platform designers classification of different abnormal situations, Exception is to be expected to unforeseen circumstances the program is running, and the developer should be captured, the appropriate treatment. Error means that under normal circumstances is unlikely to happen, most of Error will result in a non-normal procedures, unrecoverable state. So developers do not need to be captured.

Error case any error is unrecoverable processing technologies, it will certainly lead to abnormal program termination. Error checking and error type not belong to the majority occur at run time. Exception can be divided into check (checked) exceptions and does not check (unchecked) exceptions, you can check the abnormal process must be captured in the source code in the display, there is a part of the examination of the compilation. No abnormalities is called runtime exceptions, can usually be avoided encoding logic errors, according to the specific needs to determine whether to capture, and the compiler is not mandatory.

The following are common Error and Exception:

1 runtime exceptions (RuntimeException):

	NullPropagation:空指针异常;
	
	ClassCastException:类型强制转换异常
	
	IllegalArgumentException:传递非法参数异常
	
	IndexOutOfBoundsException:下标越界异常
	
	NumberFormatException:数字格式异常

2. Non-runtime exceptions:

	ClassNotFoundException:找不到指定 class 的异常
	
	IOException:IO 操作异常

3. Error (Error):

	NoClassDefFoundError:找不到 class 定义异常
	
	StackOverflowError:深递归导致栈被耗尽而抛出的异常
	
	OutOfMemoryError:内存溢出异常

The following Java code that can cause a stack overflow error.

// 通过无限递归演示堆栈溢出错误
class StackOverflow {
    public static void test(int i) {
        if (i == 0) {
            return;
        } else {
            test(i++);
        }
    }
}

public class ErrorEg {
    public static void main(String[] args) {
        // 执行StackOverflow方法
        StackOverflow.test(5);
    }
}

Run output is:

Exception in thread "main" java.lang.StackOverflowError
    at ch11.StackOverflow.test(ErrorEg.java:9)
    at ch11.StackOverflow.test(ErrorEg.java:9)
    at ch11.StackOverflow.test(ErrorEg.java:9)
    at ch11.StackOverflow.test(ErrorEg.java:9)

The above code via an infinite recursive calls eventually led to java.lang.StackOverflowError error.

Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104736051