Core Java Exception and Error What is the difference?

problem

Exception and Error What is the difference? Exceptions Exceptions What is the difference with the general run-time?

Resolve

Exception and Error inherit Throwable class. Only Throwable can be throw and catch. Exception program is normally to be expected, Error usually results in unrecoverable program. Exception can be divided into abnormalities and no abnormalities, no abnormalities is a runtime exception.

NoClassDefFoundError and ClassNotFoundException difference

NoClassDefFoundError usually occurs when the packaging error causes the compiler to find errors caused by the project can not find the package and run-time package can not be started, ClassNotFoundException occurred in the absence of such a package is loaded with Class.fromName () resulting from Exception.

The basic principles of exception handling

  1. Capture specific exception
  2. Do not swallow abnormal

E.g:

try {
 // 业务代码
 // …
 Thread.sleep(1000L);
} catch (Exception e) {
 // Ignore it
}
复制代码

Throw early, catch late 原则

  1. throw early
public void readPreferences(String fileName){
	 //...perform operations... 
	InputStream in = new FileInputStream(fileName);
	 //...read the preferences file...
}

public void readPreferences(String filename) {
	Objects. requireNonNull(filename);
	//...perform other operations... 
	InputStream in = new FileInputStream(filename);
	 //...read the preferences file...
}
复制代码
  1. catch late

Consider using custom exception, convenient location, taking care not to storm drain sensitive information. The user is not allowed information output.

Guess you like

Origin juejin.im/post/5dbbcd30f265da4d1b51cf54