The problem

What is the difference between Exception and Error? What is the difference between run-time exceptions and normal exceptions?

parsing

Both Exception and Error inherit from the Throwable class. Only Throwable can be thrown and caught. Exceptions are expected by a program under normal circumstances, and errors usually cause the program to become unrecoverable. Exceptions are classified into checkable exceptions and unchecked exceptions. Unchecked exceptions are run-time exceptions.

NoClassDefFoundError is different from ClassNotFoundException

NoClassDefFoundError usually occurs when a package error causes the package to be found at compile time and the project cannot start because the package cannot be found at run time. ClassNotFoundException occurs when, for example, an Exception is caused by loading a nonexistent package with class.fromname ().

Basic principles for exception handling

  1. Catching specific exceptions
  2. Don’t swallow abnormal

Such as:

try {
 // Business code
 / /...
 Thread.sleep(1000L);
} catch (Exception e) {
 // Ignore it
}
Copy the code

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...
}
Copy the code
  1. catch late

You can use custom exceptions to facilitate location and avoid exposing sensitive information. For example, user information cannot be output.


Every time I grow up, I want to share with you.