preface

Another year job-hopping interview season, recently took time to sort out a Java unusual interview questions. Perhaps this interview question is not enough to cover all the Java questions, but with it, I believe it is enough to deal with most of the Java interview in the market today, because this article has covered a lot of knowledge points in both depth and breadth.

JavaOOP, Java collection container, Java Exceptions, concurrent programming, Java reflection, Java serialization, JVM, Redis, Spring MVC, MyBatis, MySQL database, message middleware MQ, Dubbo, Linux, ZooKeeper, distributed & data structure and algorithm and other 25 special technical points, are xiaobian in each big factory summed up the interview question, there are a lot of fans rely on this PDF to win many big factory offer, Today, I am here to summarize and share with you! 【 Finished 】

Full version of Java interview questions address: 2021 latest interview questions collection collection.

The serial number project content link
1 The middleware Java Middleware Interview Questions (Latest version 2021) Juejin. Cn/post / 694870…
2 Micro service Java Micro Service Test Questions (updated version 2021) Juejin. Cn/post / 694906…
3 Concurrent programming Java Concurrent Programming Interview Questions (Updated 2021) Juejin. Cn/post / 695053…
4 Java based Java Basics Test Questions (2021 latest edition) Juejin. Cn/post / 695062…
5 Spring Boot Spring Boot Interview Questions (Updated 2021) Juejin. Cn/post / 695137…
6 Redis Redis Interview Questions (Updated 2021) Juejin. Cn/post / 695166…
7 Spring MVC Spring MVC Interview Questions (updated 2021) Juejin. Cn/post / 695166…
8 Spring Cloud Spring Cloud Interview Questions (Updated 2021) Juejin. Cn/post / 695245…
9 MySQL optimization MySQL optimized Interview Questions (2021 update) Juejin. Cn/post / 695246…
10 JVM JVM Performance Tuning Interview Questions (Latest version 2021) Juejin. Cn/post / 695246…
11 Linux Linux Interview Questions (Latest edition, 2021) Juejin. Cn/post / 695287…
12 Mybatis Mybatis Interview Questions (latest version 2021) Juejin. Cn/post / 695287…
13 Network programming TCP, UDP, Socket, Http Network Programming Juejin. Cn/post / 695287…
14 Design patterns Design Mode Interview Questions (latest version 2021) Juejin. Cn/post / 695544…
15 Big data 100 Big Data Interview Questions (the latest version of 2021) Juejin. Cn/post / 695544…
16 Tomcat Tomcat Interview Questions (latest version 2021) Juejin. Cn/post / 695570…
17 multithreading Multi-threaded Interview Questions (Latest edition 2021) Juejin. Cn/editor/draf…
18 Nginx Nginx_BIO_NIO_AIO Interview Questions (Updated 2021) Juejin. Cn/editor/draf…
19 memcache Memcache Interview Questions (Updated 2021) Juejin. Cn/post / 695608…
20 Java exception Java Exception Interview Questions (latest edition, 2021) Juejin. Cn/post / 695644…
21 The Java virtual machine Java Virtual Machine Interview Questions (Latest version 2021) Juejin. Cn/post / 695658…
22 Java collection Java Collection Interview Questions (Latest edition 2021) Juejin. Cn/post / 695684…
23 Git Common Commands Git Common Commands (updated 2021) Juejin. Cn/post / 695692…
24 Elasticsearch Elasticsearch Interview Questions (Updated 2021) Juejin. Cn/post / 695840…
25 Dubbo Dubbo Interview Questions (Latest edition 2021) Juejin. Cn/post / 695842…

Java exception architecture and exception keywords

1. Introduction to Java exceptions

Java exceptions are a consistent mechanism that Java provides for identifying and responding to errors. The Java exception mechanism separates exception handling code from normal business code in a program, ensuring more elegant program code and improving program robustness. When used effectively, exceptions provide a clear answer to the three questions of what, where, and why: the exception type answers “what” was thrown, the exception stack trace answers “where”, and the exception message answers “why”.

2. Java exception architecture

1. Throwable

  • Throwable is the superclass of all errors and exceptions in the Java language.
  • Throwable contains two subclasses, Error and Exception, which are usually used to indicate that an Exception has occurred.
  • Throwable contains a snapshot of the thread executing the stack when its thread was created, and it provides interfaces such as printStackTrace() to get information such as stack trace data.

2. There is an Error.

  • Definition: The Error class and its subclasses. An error in a program that cannot be handled, indicating that a critical error occurred while running the application.
  • Characteristics: This type of error typically indicates a problem with the JVM while the code is running. Examples include Virtual MachineError (Virtual machine running error), NoClassDefFoundError (class definition error), and so on. For example, OutOfMemoryError: OutOfMemoryError; StackOverflflowError: Stack overflow error. When such an error occurs, the JVM terminates the thread. These errors are unchecked exceptions, non-code errors. Therefore, the application should not handle such errors when they occur. By Java convention, we shouldn’t implement any new Error subclasses!

3. There are no exceptions.

  • Exceptions that can be caught and handled by the program itself. There are two types of exceptions: run-time and compile-time.

Runtime exception

  • Definition: The RuntimeException class and its subclasses, which represent exceptions that may occur during the JVM’s run.
  • Feature: The Java compiler does not check it. If the exception is not thrown by the throws statement, and if the exception is not caught by the try-catch statement, it will compile. Such as NullPointerException null Pointers, an abnormal ArrayIndexOutBoundException array subscript bounds, ClassCastException type conversion, an abnormal ArithmeticExecption arithmetic. This kind of exception belongs to the untested exception, which is usually caused by the program logic error. In the program, you can choose to catch and handle it or not. Although the Java compiler does not check for run-time exceptions, it is possible to declare a throw via throws, or to catch it via try-catch. If a runtime exception occurs, you need to modify the code to avoid it. For example, if the divisor is zero, you need to code to avoid it!
  • Runtimeexceptions are thrown and caught automatically by the Java virtual machine (even if we don’t write an exception catch statement at runtime!!). Most of the time, such exceptions occur when there is a problem with the code itself that should be solved logically and improved.

Compile time exception

  • Definition: Exceptions in Exception other than RuntimeException and its subclasses.
  • Features: The Java compiler checks it. If such exceptions occur in a program, such as a ClassNotFoundException (no class exception was found) or an IOException (IO stream exception), they can either be declared and thrown by throws or caught by trycatch, or they cannot be compiled. In a program, you usually do not customize this class exception, but use the system-provided exception class directly. For this exception we must manually add a catch statement to the code to handle the exception.

4. Abnormal and untested

  • All exceptions in Java can be divided into checked exceptions and uncheckedexception.

B. abnormal

  • Exceptions that must be handled by the compiler. When a program is running, it is often prone to abnormal conditions that conform to expectations. When such an exception occurs, it must be handled in some way. All exceptions except RuntimeException and its subclasses are exceptions under test. The compiler will check for such exceptions. This means that when the compiler finds an application where such an exception is possible, it will prompt you to handle the exception — either catch it with a try-catch or throw it with the method signature using the throws keyword, otherwise it will fail compilation.

No abnormal test

  • The compiler does not check for exceptions and does not require them to be handled. This means that when such an exception occurs in the program, even if we do not catch it with a try-catch or throw it with a throws. This class includes run-time exceptions (RuntimeException and subclasses) and errors (Error).

3. Java exception keyword

  • Try – For listening. The code to be listened on (code that might throw an exception) is placed inside a try block, and when an exception occurs within a try block, the exception is thrown.
  • Catch – Used to catch exceptions. Catch is used to catch exceptions that occur in a try block.
  • Fifinally – The fifinally block is always executed. It is primarily used to reclaim material resources (such as database connections, network connections, and disk files) that are opened in the try block. Only after the fifinally block is executed will it return to execute the return or throw statement in the try or catch block. If the fifinally block uses a return or throw statement to terminate the method, it will not jump back into execution and will be stopped directly.
  • Throw – Used to throw an exception.
  • Throws – used in a method signature to declare the exceptions that the method may throw.

2. Java exception handling

1. Declare exceptions

  • In general, you should catch the exceptions you know how to handle and pass along the exceptions you don’t know how to handle. You can use the throws keyword at the method signature to declare which exceptions might be thrown.

Pay attention to

  • Non-checked exceptions (Error, RuntimeException, or their subclasses) may not use the throws keyword to declare the exception to be thrown.
  • If a method has a compile-time exception, it requires try-catch/ throws handling, otherwise it results in a compile error.

2. Throw an exception

  • You can throw exceptions if you feel you can’t solve them and the caller doesn’t need to handle them.
  • The throw keyword is used to throw an exception of type Throwable inside a method. Any Java code can throw an exception with a throw statement.

3. Catch exceptions

Programs usually do not report errors before they are run, but after they are run, some unknown error may occur, but you do not want to throw directly to the next level, so you need to try… The catch… And then handle the exception according to different exception cases.

4. How to select an exception type

You can choose whether to catch, declare, or throw an exception based on the following figure

5. Common exception handling methods

Direct throw exception

In general, you should catch the exceptions you know how to handle and pass along the exceptions you don’t know how to handle. You can use the throws keyword at the method signature to declare which exceptions might be thrown.

private static void readFile(String filePath) throws IOException { File file = new File(filePath); String result; BufferedReader reader = new BufferedReader(new FileReader(file)); while((result = reader.readLine())! =null) { System.out.println(result); } reader.close(); }Copy the code

Encapsulate an exception and then throw it

Sometimes we throw an exception from a catch in order to change the type of the exception. It is mainly used in the integration of multiple systems. When a certain subsystem fails, there may be multiple types of exceptions. The unified exception type can be used to expose the outside without exposing too many internal exception details.

private static void readFile(String filePath) throws MyException { try { // code } catch (IOException e) { MyException ex = new MyException("read file failed."); ex.initCause(e); throw ex; }}Copy the code

Catch exceptions

Multiple exception types can be caught in a single try-catch block and handled differently for each type of exception

private static void readFile(String filePath) {
try {
// code
} catch (FileNotFoundException e) {
// handle FileNotFoundException
} catch (IOException e){
// handle IOException
}
}
Copy the code

Can capture a variety of types that same catch exceptions, separated by |

private static void readFile(String filePath) { try { // code } catch (FileNotFoundException | UnknownHostException e) {  // handle FileNotFoundException or UnknownHostException } catch (IOException e){ // handle IOException } }Copy the code

Custom exception

It is customary to define an exception class with two constructors, a constructor that takes no arguments and a constructor with detailed descriptions (Throwable’s toString method prints these details, which are useful for debugging).

public class MyException extends Exception {
public MyException(){ }
public MyException(String msg){
super(msg);
}
// ...
}
Copy the code

try-catch-fifinally

When an exception occurs ina method, the code after the exception is no longer executed. If some local resources have been obtained and need to be freed, the code that frees the local resources needs to be called both at the normal end of the method and in the catch statement, which can be cumbersome. Fifinally statements can solve this problem.

private static void readFile(String filePath) throws MyException { File file = new File(filePath); String result; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); while((result = reader.readLine())! =null) { System.out.println(result); } } catch (IOException e) { System.out.println("readFile method catch block."); MyException ex = new MyException("read file failed."); ex.initCause(e); throw ex; } finally { System.out.println("readFile method finally block."); if (null ! = reader) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); }}}}Copy the code
  • When this method is called, if an exception occurs while reading the file, the code goes into the catch block and then into the fifinally block. If no exception occurs when the file is read, the catch block is skipped and the fifinally block goes directly. So the code in FifianLly executes regardless of whether an exception occurs in the code.
  • Does the code in fiFinally execute if the catch block contains a return statement? Modify the catch clause in the above code as follows:
catch (IOException e) {
System.out.println("readFile method catch block.");
return;
}
Copy the code
  • Call the readFile method to see if the fifinally clause executes when a return statement is called in the catch clause
readFile method catch block.
readFile method finally block.
Copy the code
  • As you can see, the FIfinally clause executes even if the catch contains a return statement. If fiFinally also contains a return statement, the return in fifinally overrides the previous return.

try-with-resource

In the example above, the close method in fifinally might also throw an IOException, overriding the original exception. JAVA 7 provides a more elegant way to automatically release resources from classes that implement the AutoCloseable interface.

private static void tryWithResourceTest(){
	try (Scanner scanner = new Scanner(new FileInputStream("c:/abc"),"UTF-8")){
		// code
	}
	catch (IOException e){
		// handle exception
	}
}
Copy the code
  • When the try block exits, the scanner. Close method is automatically called. Unlike placing the scanner. Close method in the fifinally block, if the scanner. The suppressed exception will be added to the original one by the addresume Pressed method and if you want to get the list of suppressed exceptions you can call getSuppressed to do that.

Three, Java exception often meet test questions

1. What is the difference between Error and Exception?

  • Errors of the Error type are usually vm related errors, such as system crash, memory shortage, stack overflow, etc. The compiler does not detect these errors, and JAVA applications should not catch these errors. Once these errors occur, the application will be terminated and cannot be recovered by the application itself.
  • Errors in the Exception class are something that can be caught and handled in an application, and usually when encountered, they should be handled so that the application can continue to function normally.

2. What is the difference between run-time exceptions and general exceptions (checked exceptions)?

  • Runtime exceptions include the RuntimeException class and its subclasses, which represent exceptions that may occur during the runtime of the JVM. The Java compiler does not check for runtime exceptions.
  • The checked Exception is an Exception in Exception other than RuntimeException and its subclasses. The Java compiler checks for checked exceptions.
  • The difference between a RuntimeException and a checked exception: whether it is mandatory that the caller must handle the exception, if so, use the checked exception, otherwise choose an unchecked exception (RuntimeException). In general, if there are no special requirements, we recommend using a RuntimeException.

3. How does the JVM handle exceptions?

  • If an exception occurs in a method, the method creates an exception object and passes it to the JVM. This exception object contains the exception name, the exception description, and the state of the application at the time the exception occurred. The process of creating an exception object and passing it to the JVM is called throwing an exception. There may be a series of method calls that end up in the method that throws the exception, and this ordered list of method calls is called the call stack.
  • The JVM looks down the call stack to see if there is code that can handle exceptions, and if so, calls the exception handling code. When the JVM finds a generation that can handle exceptions, it passes it the exception that occurs. If the JVM does not find a block of code that can handle the exception, the JVM passes the exception to the default exception handler (which is part of the JVM), which prints out the exception information and terminates the application.

4. What’s the difference between throw and throws?

  • Exception handling in Java includes, in addition to catching and handling exceptions, declaring and throwing exceptions. You can declare the exception to be thrown on a method by using the throws keyword, or throw an exception object inside a method by throwing it.

Throws keyword and throw the key words on the use of several differences are as follows:

  • The throw keyword is used inside a method and can only be used to throw one type of exception. It is used to throw an exception in a method or code block. Both checked and unchecked exceptions can be thrown.
  • Throws The throws keyword is used for a method declaration. Multiple exceptions can be thrown. It is used to identify the list of possible exceptions thrown by the method. A method uses the throws keyword to identify the list of exceptions that can be thrown. Methods that call this method must contain code that can handle exceptions, otherwise, the corresponding exception must be declared in the method signature using the throws keyword.

5. What is the difference between final, finally and Finalize?

  • Fifinal can modify classes, variables, and methods. A modified class means that the class cannot be inherited, a modified method means that the method cannot be overridden, and a modified variable means that the variable is a constant and cannot be reassigned.
  • Fifinally is usually used ina try-catch block of code. When an exception is handled, we will always execute the code in the fifinally block, which means that the block will execute regardless of whether an exception occurs. It is usually used to hold code that closes the resource.
  • Fifinalize () is a method belonging to the Object class, which is the parent class of all classes. In Java, fiFinalize () method is allowed to do the necessary cleaning work before garbage collector clears the Object out of memory.

6. NoClassDefFoundError and ClassNotFoundException?

  • NoClassDefFoundError is an exception of type Error that was raised by the JVM and should not be attempted to catch.
  • The cause of this exception is that the JVM or ClassLoader cannot find the definition of a class in memory when trying to load the class. This action occurs during the runtime, that is, the class exists at compile time, but cannot be found at run time. The possible cause is that the class is deleted after mutation.
  • ClassNotFoundException is a checked exception that needs to be caught and handled explicitly with a try-catch or declared with the throws keyword in the method signature. When using the Class. The class.forname, this loadClass. Or this fifindSystemClass dynamic Class is loaded into memory, didn’t find the Class through the incoming Class path parameters, throws the exception; Another possible reason to throw this exception is if a class has been loaded into memory by one classloader and another is trying to load it.

7. What part of try-catch-finally can be omitted?

8. In a try-catch-finally, if a return is ina catch, will finally be executed?

9. = = = = = = = = = =

10. What are some common Runtimeexceptions?

  • ClassCastException
  • IndexOutOfBoundsException (an array)
  • NullPointerException
  • ArrayStoreException(data store exception, array operation type inconsistent)
  • And the abnormal BufffferOverflflowException IO operations

11. What are the common Java exceptions

  • Java. Lang. IllegalAccessError: illegal access errors. This exception is thrown when an application attempts to access, modify, or call a class’s Field, but violates the visibility declaration for the Field or method.
  • Java. Lang. InstantiationError: instantiation errors. This exception is thrown when an application attempts to construct an abstract class or interface using Java’s new operator.
  • Java. Lang. OutOfMemoryError: out of memory error. This error is thrown when the available memory is insufficient for the Java Virtual Machine to allocate to an object.
  • Java. Lang. StackOverflflowError: stack overflow error. This error is thrown when an application recursive call is so deep that the stack overflows or gets stuck in an infinite loop.
  • Java. Lang. ClassCastException: class abnormal shape. If you have classes A and B (A is not A parent or subclass of B) and O is an instance of A, then this exception is thrown when you force constructing O as an instance of class B. This exception is often referred to as a cast exception.
  • Java. Lang. ClassNotFoundException: can’t find the abnormal class. This exception is thrown when an application attempts to construct a class based on the class name as a string, but after traversal of the CLASSPAH cannot find a class file with the same name.
  • Java. Lang. ArithmeticException: arithmetic abnormal conditions. Divide an integer by zero, etc.
  • Java. Lang. ArrayIndexOutOfBoundsException: array index cross-border anomalies. Thrown when the index on an array is negative or greater than or equal to the array size.
  • Java. Lang. IndexOutOfBoundsException: index cross-border anomalies. This exception is thrown when the index value of a sequence is less than 0 or greater than or equal to the sequence size.
  • Java. Lang. InstantiationException: instantiate the exception. This exception is thrown when an attempt is made to create an instance of a class that is an abstract class or interface through the newInstance() method.
  • Java. Lang. NoSuchFieldException: attributes, there is no exception. This exception is thrown when a nonexistent property of a class is accessed.
  • Java. Lang. NoSuchMethodException: there is no exception. This exception is thrown when a nonexistent method of a class is accessed. –
  • Java. Lang. NullPointerException: null pointer exception. When an application tries to use null where an object is required,
  • Throw this exception. Examples include calling instance methods of null objects, accessing properties of null objects, calculating the length of null objects, throwing null statements, and so on.
  • Java. Lang. A NumberFormatException: abnormal number format. This exception is thrown when an attempt is made to convert a String to the specified numeric type and the String does not satisfy the format required by the numeric type.
  • Java. Lang. StringIndexOutOfBoundsException: string index crossed the exception. This exception is thrown when a character in a string is accessed using an index value that is less than 0 or greater than or equal to the sequence size.

Fourth, Java exception handling best practices

1. Clean up resources in the finally block or use the try-with-resource statement

2. Prioritize clear exceptions

3. Document the exception

4. Use descriptive messages to throw exceptions

5. Catch the most specific exceptions first

6. Do not capture the Throwable class

7. Don’t ignore exceptions

8. Do not log and throw exceptions

9. Do not discard the original exception when wrapping it

10. Do not use exceptions to control the flow of the program

You should not use exceptions to control the execution of your application. For example, using an exception when you should use an if statement is a bad habit and can seriously affect the performance of your application.

11. Use standard exceptions

Don’t define your own exceptions if using built-in exceptions can solve the problem. The Java API provides hundreds of exception types for different situations. Use the exceptions provided by the Java API as your first step in development. If the standard exceptions do not meet your requirements, create your own custom exceptions. Use standard exceptions whenever possible to help new developers understand the project code.

12. An exception affects performance

13. To summarize

  • To sum up, there are many different situations to consider when you throw or catch exceptions, and most of them are to improve the readability of your code or the usability of your API.
  • Exceptions are not only an error control mechanism, but also a communication medium. Therefore, in order to work better with colleagues, a team must develop a set of best practices and rules so that team members can understand these general concepts and use them in their work.

Exception Handling – Alibaba Java Development Manual