In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the abnormal interview questions in the latest version of 2021 java". In the daily operation, I believe that many people have doubts about the abnormal interview questions in the latest version of 2021 java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "what are the abnormal interview questions in the latest version of 2021 java?" Next, please follow the editor to study!
1. Java exception architecture and exception keywords
1. Introduction to Java exception
Java exception is a consistent mechanism provided by Java to identify and respond to errors. The Java exception mechanism can separate the exception handling code from the normal business code, ensure that the program code is more elegant, and improve the robustness of the program. In the case of effective use of the exception, the exception can clearly answer the three questions what, where, and why: the exception type answered "what" was thrown, the exception stack trace answered "where" thrown, and the exception message answered "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 (error) and Exception (exception), which are usually used to indicate that an exception has occurred.
Throwable contains a snapshot of the execution stack of its thread when it is created, and it provides interfaces such as printStackTrace () to obtain information such as stack trace data.
2. Error (error)
Definition: Error class and its subclasses. An unhandled error in the program indicates that a serious error occurred while running the application.
Features: this kind of error generally indicates that there is a problem with JVM when the code is running. There are usually Virtual MachineError (virtual machine running error), NoClassDefFoundError (class definition error) and so on. For example, OutOfMemoryError: out of memory error; StackOverflflowError: stack overflow error. When such an error occurs, JVM terminates the thread. These errors are unchecked exceptions and non-code errors. Therefore, when such errors occur, the application should not deal with such errors. According to Java convention, we should not implement any new Error subclasses!
3. Exception (exception)
Exceptions that can be caught and handled by the program itself. Exception exceptions fall into two categories: run-time exceptions and compile-time exceptions.
Runtime exception
Definition: the RuntimeException class and its subclasses, which represent exceptions that may occur during the run of JVM.
Features: the Java compiler does not check it. That is, when such an exception may occur in the program, it will be compiled if it is "not thrown through the throws declaration" or "caught with the try-catch statement". For example, NullPointerException null pointer exception, ArrayIndexOutBoundException array subscript out of bounds exception, ClassCastException type conversion exception, ArithmeticExecption arithmetic exception. This kind of exception belongs to unchecked exception, which is usually caused by program logic error, and can be captured or not handled in the program. Although the Java compiler does not check for run-time exceptions, we can declare and throw it through throws, or we can catch it through try-catch. If a runtime exception is generated, it needs to be avoided by modifying the code. For example, if the divisor is zero, you need to avoid it through code!
RuntimeException exceptions are automatically thrown and caught by the Java virtual machine (even if we don't write exception catch statements run, an error is thrown! The vast majority of such exceptions occur when there is a problem with the code itself that should be logically solved and improved.
Compile-time exception
Definition: exceptions in Exception except RuntimeException and its subclasses.
Features: the Java compiler checks it. If such an exception occurs in the program, such as ClassNotFoundException (no specified class exception found), IOException (IO stream exception), it is either declared and thrown by throws or captured by trycatch, otherwise it cannot be compiled. In a program, this kind of exception is usually not customized, but the exception class provided by the system is used directly. For this exception, we must manually add a capture statement to the code to handle the exception.
4. Abnormal and non-checked abnormalities
All abnormalities of Java can be divided into detected abnormalities (checkedexception) and non-examined anomalies (uncheckedexception).
Abnormal detected
An exception that the compiler requires that must be handled. The correct program in the process of running, often easy to occur, in line with the expected abnormal situation. Once such an exception occurs, it must be handled in some way. Except for RuntimeException and its subclasses, other Exception anomalies are detected. The compiler will check for such exceptions, that is, when the compiler detects that such exceptions may be found somewhere in the application, it will prompt you to handle this exception-either using try-catch capture or using the throws keyword in the method signature, otherwise the compilation fails.
Unchecked anomaly
The compiler does not check and does not require an exception that must be handled, which means that when such an exception occurs in the program, even if we do not catch it with try-catch or use throws to throw the exception, the compilation will pass normally. Such exceptions include run-time exceptions (RuntimeException and its subclasses) and errors (Error).
3. Java exception keyword
Try-used for monitoring. The code to be listened for (the code that may throw an exception) is placed within the try statement block, and when an exception occurs within the try statement block, the exception is thrown.
Catch-used to catch exceptions. Catch is used to catch exceptions that occur in try statement blocks.
Blocks of fifinally-fifinally statements are always executed. It is mainly used to recover material resources (such as database connections, network connections and disk files) opened in try blocks. Only after the execution of the fifinally block, will you come back to execute the return or throw statements in the try or catch blocks. If the statements with termination methods such as return or throw are used in the fifinally, the execution will not be skipped back and will be stopped directly.
Throw-used to throw an exception.
Throws-used in method signatures to declare exceptions that may be thrown by the method.
Second, Java exception handling 1. Declare exception
In general, exceptions that know how to handle should be caught, and exceptions that don't know how to handle should be passed on. Passing an exception can declare an exception that may be thrown using the throws keyword at the method signature.
Be careful
Non-checked exceptions (Error, RuntimeException, or their subclasses) cannot use the throws keyword to declare the exception to be thrown.
If a method has a compile-time exception, it needs to be handled by try-catch/ throws, otherwise it will result in a compilation error.
two。 Throw an exception
If you don't think you can solve some exception problems and don't need to be handled by the caller, you can throw an exception.
The function of the throw keyword is to throw an exception of type Throwable inside the method. Any Java code can throw an exception through a throw statement.
3. Catch exception
Programs usually do not report errors before running, but some unknown errors may occur after running, but they do not want to be thrown directly to the next level, so you need to pass try. Catch... The exception is caught in the form of, and then handled according to different exception situations.
4. How to choose the exception type
You can choose whether to catch, declare or throw an exception according to the following figure
5. Common exception handling methods
Throw an exception directly
In general, exceptions that know how to handle should be caught, and exceptions that don't know how to handle should be passed on. Passing an exception can declare an exception that may be thrown using the throws keyword at the method signature.
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 ();}
Encapsulate the exception and then throw
Sometimes we throw an exception from the catch in order to change the type of the exception. It is often used in multi-system integration, when a subsystem fails, there may be a variety of exception types, which can be exposed with a unified exception type 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;}}
Catch exception
Multiple exception types can be caught in a try-catch statement block, and different types of exceptions can be handled differently.
Private static void readFile (String filePath) {try {/ / code} catch (FileNotFoundException e) {/ / handle FileNotFoundException} catch (IOException e) {/ / handle IOException}}
Multiple types of exceptions can also be caught with the same catch, separated by |
Private static void readFile (String filePath) {try {/ / code} catch (FileNotFoundException | UnknownHostException e) {/ / handle FileNotFoundException or UnknownHostException} catch (IOException e) {/ / handle IOException}}
Custom exception
Traditionally, defining an exception class should contain two constructors, a no-parameter constructor and a constructor with detailed description information (Throwable's toString method prints these details, which is useful when debugging)
Public class MyException extends Exception {public MyException () {} public MyException (String msg) {super (msg);} / /.}
Try-catch-fifinally
When an exception occurs in the method, the code after the exception will no longer be executed. If some local resources need to be released before, you need to call the code to release the local resources at the normal end of the method and in the catch statement, which is tedious. The fifinally statement 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 () }}
When this method is called, if an exception occurs when reading the file, the code will enter the catch code block, and then enter the fifinally code block; if no exception occurs when reading the file, it will skip the catch code block and directly enter the fifinally code block. So the code in fifianlly executes regardless of whether an exception occurs in the code.
If the catch code block contains return statements, will the code in fifinally still execute? Modify the catch clause in the above code as follows:
Catch (IOException e) {System.out.println ("readFile method catch block."); return;}
Call the readFile method to observe whether the fifinally clause executes when the return statement is called in the catch clause
ReadFile method catch block.readFile method finally block.
As you can see, even if the return statement is included in the catch, the fifinally clause is still executed. If the fifinally also contains a return statement, the return in the fifinally will overwrite the previous return.
Try-with-resource
In the above example, the close method in fifinally may also throw an IOException, overwriting the original exception. JAVA 7 provides a more elegant way to automatically release resources, which need to be 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}}
When the try code block exits, the scanner.close method is automatically called. Unlike putting the scanner.close method in the fifinally code block, if scanner.close throws an exception, it will be suppressed and the original exception will still be thrown. The suppressed exception is added to the original exception by the addSusppressed method. If you want to get the list of suppressed exceptions, you can call the getSuppressed method to get it.
3. Java often meet questions 1. What is the difference between Error and Exception?
Error type errors are usually virtual machine related errors, such as system crash, insufficient memory, stack overflow, etc., the compiler will not detect such errors, and JAVA applications should not catch such errors. Once such errors occur, the application is usually terminated and cannot be recovered by the application itself.
Errors in the Exception class can be caught and handled in the application, and such errors are usually encountered and should be handled so that the application can continue to run normally.
two。 What is the difference between a runtime exception and a general exception (checked exception)?
Run-time exceptions include the RuntimeException class and its subclasses, which represent exceptions that may occur during the run of JVM. The Java compiler does not check for run-time exceptions.
The detected exception is the exception in Exception except RuntimeException and its subclasses. The Java compiler checks for checked exceptions.
The difference between the RuntimeException exception and the checked exception: whether to force the caller to handle this exception, if the caller is forced to handle it, then use the checked exception, otherwise select the non-checked exception (RuntimeException). Generally speaking, if there are no special requirements, we recommend using RuntimeException exceptions.
3. How does JVM handle exceptions?
If an exception occurs in a method, the method creates an exception object and passes it to JVM, which contains the exception name, the exception description, and the state of the application when the exception occurs. The process of creating an exception object and passing it to JVM is called throwing an exception. There may be a series of method calls that eventually enter the method that throws an exception, and the ordered list of method calls is called the call stack.
JVM will follow the call stack to see if there is any code that can handle the exception, and if so, call the exception handling code. When JVM finds a generation that can handle an exception, it passes the exception that occurred to it. If JVM does not find a block of code that can handle the exception, JVM transfers the exception to the default exception handler (which is part of JVM), which prints the exception message and terminates the application.
4. What is the difference between throw and throws?
Exception handling in Java includes not only catching and handling exceptions, but also declaring and exiting exceptions. You can declare the exception to be exported by the method through the throws keyword, or expose the exception object within the method through throw.
Several differences in the use of the throws keyword and the throw keyword are as follows:
The throw keyword is used inside a method and can only be used to throw an exception in a method or block of code. Both checked and unchecked exceptions can be thrown.
The throws keyword is used on method declarations, and multiple exceptions can be thrown to identify a list of exceptions that the method may throw. A method uses throws to identify the list of exceptions that may be thrown. The method that calls the method must contain code that can handle the exception, otherwise the corresponding exception will be declared with the throws keyword in the method signature.
5. What's the difference between final, finally and finalize?
Fifinal can modify classes, variables, and methods. The modifier class indicates that the class cannot be inherited, the modifier method indicates that the method cannot be overridden, and the modifier variable indicates that the variable is a constant that cannot be re-assigned.
Fifinally generally acts in the try-catch code block, when dealing with exceptions, we usually must execute the code method fifinally code block, indicating that no matter whether there is an exception, the code block will be executed, generally used to store some closed resources of the code.
Fifinalize is a method, a method of the Object class, and the Object class is the parent of all classes, and the Java allows you to use the fifinalize () method to do the necessary cleanup before the garbage collector clears the object out of memory.
6. The difference between NoClassDefFoundError and ClassNotFoundException?
NoClassDefFoundError is an exception of type Error that is caused by JVM and should not be attempted to catch.
The reason for this exception is that when JVM or ClassLoader tries to load a class, the definition of the class cannot be found in memory. The action occurs during the run time, that is, the class exists at compile time, but cannot be found at run time. It may be caused by the deletion of the mutation.
ClassNotFoundException is a checked exception that needs to be caught and handled explicitly using try-catch, or declared with the throws keyword in the method signature. When a class is dynamically loaded into memory using Class.forName, ClassLoader.loadClass, or ClassLoader.fifindSystemClass, the exception is thrown if the class is not found through the passed classpath parameters; another possible reason for throwing the exception is that a class has been loaded into memory by one class loader and another loader tries to load it.
7. Which part of try-catch-finally can be omitted?
8. In try-catch-finally, if there is return in catch, will finally still execute it?
9. Class ExampleA inherits from Exception, class ExampleB inherits from ExampleA.
10. What are the common RuntimeException?
ClassCastException (class conversion exception)
IndexOutOfBoundsException (array out of bounds)
NullPointerException (null pointer)
ArrayStoreException (data storage exception, inconsistent array type)
There are also BufffferOverflflowException exceptions for IO operations
11. What are the common exceptions in Java
Java.lang.IllegalAccessError: illegal access error. This exception is thrown when an application attempts to access, modify, or call the Field of a class, but violates the visibility declaration of the domain or method.
Java.lang.InstantiationError: instantiation error. This exception is thrown when an application attempts to construct an abstract class or interface through the new operator of Java.
Java.lang.OutOfMemoryError: out of memory error. This error is thrown when there is not enough memory available 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 falls into a dead loop.
Java.lang.ClassCastException: class shape exception. If there are classes An and B (An is not a parent or subclass of B) and O is an instance of A, this exception is thrown when O is forced to be constructed as an instance of class B. This exception is often referred to as a cast exception.
Java.lang.ClassNotFoundException: class exception not found. This exception is thrown when the application attempts to construct a class based on a class name in the form of a string, and the class file with the corresponding name cannot be found after traversing the CLASSPAH.
Java.lang.ArithmeticException: arithmetic condition exception. For example: integer divided by zero and so on.
Java.lang.ArrayIndexOutOfBoundsException: array index out of bounds exception. Thrown when the index of the array is negative or greater than or equal to the size of the array.
Java.lang.IndexOutOfBoundsException: index out of bounds exception. The exception is thrown when the index value accessing a sequence is less than 0 or greater than or equal to the sequence size.
Java.lang.InstantiationException: instantiates an 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: there are no exceptions to the property. This exception is thrown when a non-existent property of a class is accessed.
Java.lang.NoSuchMethodException: there are no exceptions to the method. This exception is thrown when a non-existent method of a class is accessed. -
Java.lang.NullPointerException: null pointer exception. When the application attempts to use null where the object is required
The exception is thrown. For example, call the instance method of the null object, access the properties of the null object, calculate the length of the null object, use the throw statement to throw the null, and so on.
Java.lang.NumberFormatException: the number format is abnormal. This exception is thrown when an attempt is made to convert an String to the specified numeric type and the string does not meet the format required by the numeric type.
Java.lang.StringIndexOutOfBoundsException: string index out of bounds exception. The exception is thrown when an index value is used to access a character in a string 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 finally blocks or use try-with-resource statements
two。 Give priority to specific exceptions
3. Document the exception
4. Use a descriptive message to throw an exception
5. Give priority to catching the most specific exception
6. Do not capture the Throwable class
7. Don't ignore exceptions
8. Do not record and throw an exception
9. Do not discard the original exception when you wrap the exception
10. Do not use the flow of the exception control program
Exceptions should not be used to control the execution flow of an application. For example, when you are supposed to use if statements to determine conditions, you use exception handling, which is a very bad habit and will seriously affect the performance of the application.
11. Use standard exceptions
If you can solve the problem with built-in exceptions, don't define your own exceptions. Java API provides hundreds of exception types for different situations, first use the exceptions provided by Java API as much as possible in development, and create your own custom exceptions if the standard exceptions do not meet your requirements. Use standard exceptions as much as possible to help new developers understand the project code.
twelve。 Exceptions can affect performance
13. Summary
To sum up, when you throw or catch an exception, there are many different situations to consider, and most of the things are to improve the readability of the code or the availability of the API.
Exception is not only an error control mechanism, but also a communication medium. Therefore, in order to work better with colleagues, a team must develop best practices and rules so that team members can understand these common concepts and use them at work.
Exception handling-Alibaba Java Development Manual
At this point, the study on "what are the abnormal interview questions in the latest version of 2021 java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.