In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "summary of knowledge points related to Java anomalies". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
1. Java exception architecture and exception keywords
Introduction to Java exception
Java exception architecture
1 、 Throwable
2. Error (error)
3. Exception (exception)
4. Abnormal and non-checked abnormalities
Java exception keyword
2. Java exception handling
Declare exception
Throw an exception
Catch exception
How to choose the exception type
Common exception handling methods
1. Throw an exception directly
2. Encapsulate the exception and then throw it
3. Catch exception
4. Custom exception
5 、 try-catch-finally
6 、 try-with-resource
Third, Java often meets with test questions.
1. What is the difference between Error and Exception?
2. What is the difference between a runtime exception and a general exception (detected exception)?
3. How does JVM handle exceptions?
4. What is the difference between throw and throws?
5. What's the difference between final, finally and finalize?
6. The difference between NoClassDefFoundError and ClassNotFoundException?
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 Exception, class ExampleB inherits ExampleA.
10. State the running result of the following code
11. What are the common RuntimeException?
12. What are the common exceptions in Java
13. The difference of Throwable, Error, Exception and RuntimeException in Java exception
Fourth, Java exception handling best practices
1. Clean up resources in the finally block or use try-with-resource statements
(1) use finally code blocks
(2) try-with-resource syntax of Java 7
2. Give priority to specific exceptions
3. Document the exception
4. Use descriptive messages to throw an exception
5. Give priority to catching the most specific exceptions
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 the package is abnormal
Do not use the flow of the exception control program
11. Use standard exceptions
12. Exceptions can affect performance
13. Summary
Exception handling-Alibaba Java development manual
1. Brief introduction of Java exception architecture and exception keyword 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 exceptions, exceptions can clearly answer the three questions of what,where,why:
The exception type answers "what" is thrown
The exception stack trace answered "where" thrown
The exception message answered "Why" will be thrown
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; StackOverflowError: 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 will be automatically thrown and caught by the Java virtual machine, and errors will be thrown even if we do not write exception catch statements!
The most common occurrence of such exceptions is that there is something wrong with the code itself, which should be solved and improved logically.
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 try-catch, 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.
With the exception of RuntimeException and its subclasses, all Exception exceptions are checked, and the compiler checks for such exceptions.
That is, when the compiler detects that such an exception may occur somewhere in the application, it will prompt you to handle this exception.
Either use the try-catch capture or use the throws keyword in the method signature to throw, otherwise the compilation fails.
Unchecked anomaly
Exceptions that are not checked by the compiler and are not required to be handled.
That is to say, when such an exception occurs in the program, even if we do not catch it with try-catch, we do not use throws to throw the exception, and the compilation will pass normally.
Such exceptions include run-time exceptions (RuntimeException and its subclasses) and errors (Error).
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.
Finally:finally statement blocks 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 finally block is completed, will you come back to execute the return or throw statements in the try or catch block
If a statement with a termination method such as return or throw is used in finally, it will not jump back to execution and will simply stop.
Throw: used to throw an exception.
Throws: used in method signatures to declare exceptions that may be thrown by the method.
2. Java exception handling
Java handles exceptions through the object-oriented method. Once the method throws an exception, the system automatically finds a suitable exception handler (Exception Handler) according to the exception object to handle the exception, classifies all kinds of exceptions, and provides a good interface.
In Java, each exception is an object, which is an instance of the Throwable class or its subclasses.
When an exception occurs in a method, an exception object is thrown, which contains exception information. The method that calls this object can catch the exception and implement it.
Deal with it.
The exception handling of Java is implemented through five keywords: try, catch, throw, throws and finally.
In Java application, the exception handling mechanism is divided into declaring exception, throwing exception and catching exception.
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.
Note:
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.
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.
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.
Then you need to go through try... Catch... The exception is caught in the form of, and then handled according to different exception situations.
How to choose the exception type
You can choose whether to catch, declare or throw an exception according to the following figure
Common exception handling methods 1. 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.
Public static void readFile (String filePath) throws IOException {BufferedReader reader = new BufferedReader (new FileReader (filePath)); String res; while ((res = reader.readLine ())! = null) {System.out.println (res);} reader.close ();} 2, 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 mostly 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.
Customize an exception MyException
Public class MyException extends Exception {public MyException () {super ();} public MyException (String message) {super (message);}}
Use custom exceptions to encapsulate exceptions
Public static void readFile (String filePath) throws MyException {BufferedReader reader = null; String res; try {reader = new BufferedReader (new FileReader (filePath)); while ((res = reader.readLine ())! = null) {System.out.println (res);} catch (IOException e) {MyException myException = new MyException ("failed to read file!") ; myException.initCause (e); throw myException;} try {reader.close ();} catch (IOException e) {e.printStackTrace ();}} 3, catch an exception
Multiple exception types can be caught in a try-catch statement block, and different types of exceptions can be handled differently.
Public static void readFile (String filePath) {try {/ / do} catch (FileNotFoundException e) {/ / handle FileNotFoundException} catch (IOException e) {/ / handle IOException}}
Multiple types of exceptions can also be caught with the same catch, separated by |
Public static void readFile (String filePath) {try {/ / do} catch (FileNotFoundException | UnknownHostException e) {/ / handle FileNotFoundException or UnknownHostException} catch (IOException e) {/ / handle IOException}} 4, custom exception
Traditionally, defining an exception class should contain two constructors, a no-parameter constructor and a constructor with detailed description information
The toString method of Throwable prints these details, which are useful when debugging.
Public class MyException extends Exception {public MyException () {super ();} public MyException (String message) {super (message);}} 5, try-catch-finally
When an exception occurs in the method, the code after the exception will no longer be executed. If some local resources have been acquired before, they need to be released.
Then the code that releases the local resources needs to be called at the normal end of the method and in the catch statement, which makes the code more tedious.
The finally statement can solve this problem.
Public static void readFile (String filePath) throws MyException {BufferedReader reader = null; String res; try {reader = new BufferedReader (new FileReader (filePath)); while ((res = reader.readLine ())! = null) {System.out.println (res);} catch (IOException e) {System.out.println ("catch Code Block") MyException myException = new MyException ("failed to read file!") ; myException.initCause (e); throw myException;} finally {System.out.println ("finally code 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 finally code block
If no exception occurs when reading the file, the catch code block is skipped and goes directly to the finally code block.
So the code in fianlly executes regardless of whether an exception occurs in the code.
If the catch code block contains return statements, will the code in finally still execute? Modify the catch clause in the above code as follows:
Catch (IOException e) {System.out.println ("catch code block"); return;}
Call the readFile method to observe whether the finally clause executes when the return statement is called in the catch clause
Catch code block finally code block
As you can see, even if the return statement is included in the catch, the finally clause is still executed.
If the finally also contains a return statement, the return in the finally overrides the previous return.
6 、 try-with-resource
In the above example, the close method in finally 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.
Public static void tryWithResourceTest () {try {Scanner scanner = new Scanner (new FileInputStream ("new FileInputStream /"), "UTF-8");} catch (IOException e) {/ / handle IOException}}
When the try code block exits, the scanner.close method is called automatically, unlike putting the scanner.close method in the finally code block
If scanner.close throws an exception, it will be suppressed and the original exception will still be thrown.
Suppressed exceptions are added to the original exception by the addSusppressed method. If you want to get a list of suppressed exceptions,
You can call the getSuppressed method to get.
Question 1. What is the difference between Java and Exception?
Error type errors are usually virtual machine related errors, such as system crash, insufficient memory, stack overflow, etc.
The compiler does not detect such errors, and JAVA applications should not catch such errors
Once such an error occurs, 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 are often encountered
It should be processed so that the application can continue to run normally.
2. What is the difference between a runtime exception and a general exception (detected 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 a RuntimeException exception and an exception being detected: whether to force the caller to handle this exception
If the caller is forced to handle it, the checked exception is used, otherwise the non-checked exception (RuntimeException) is selected.
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
The exception object contains the name of the exception, the description of the exception, 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 code that can handle an exception, it passes the exception to it.
If JVM does not find a code block that can handle the exception, JVM passes the exception to the default exception handler
The default exception handler is part of the JVM, and the default exception handler prints out the exception information 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 checking exceptions.
The exception to be thrown by the method can be declared on the method through the throws keyword, or the exception object can be declared inside 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, which is used to throw an exception in a method or code block
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, and the method that calls the method must contain code that can handle the exception
Otherwise, declare the corresponding exception in the method signature with the throws keyword.
5. What's the difference between final, finally and finalize?
Final 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 modifies variables.
Indicates that the variable is a constant and cannot be reassigned.
Finally generally acts in the try-catch code block. When handling exceptions, we usually put the code method finally code that must be executed.
Block, indicating that the code block will be executed regardless of whether an exception occurs or not, and is generally used to store some code that closes the resource.
Finalize is a method, belonging to a method of the Object class, while the Object class is the parent of all classes, and finalize () is allowed in Java.
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 the definition of a class cannot be found in memory when JVM or ClassLoader tries to load it.
This action occurs during the run time, that is, the class exists at compile time, but can not be found at run time. It may be caused by the mutation and deletion.
ClassNotFoundException is a checked exception that needs to be caught and handled explicitly using try-catch
Or declare it with the throws keyword in the method signature.
When dynamically loading classes into memory using Class.forName,ClassLoader.loadClass or ClassLoader.findSystemClass
If the class is not found through the classpath parameter passed in, the exception will be thrown
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?
Catch can be omitted.
Reason
To put it more strictly, try is only suitable for handling run-time exceptions, while try+catch is suitable for handling run-time exceptions + normal exceptions.
In other words, if you only use try to handle ordinary exceptions without catch handling, compilation will not pass.
Because the compiler dictates that if you choose to catch a normal exception, you must display the declaration with catch for further processing.
Run-time exceptions are not specified at compile time, so catch can be omitted, and it is understandable for you to add the catch compiler.
In theory, the compiler doesn't like any code and thinks there may be potential problems, so even if you add try to all the code
At runtime, the code is nothing more than a layer of skin on the basis of normal operation.
But once you add try to a piece of code, you explicitly promise the compiler to catch the exception that may be thrown by the code, rather than throwing it up.
If it is a normal exception, the compiler requires that it must be captured with catch for further processing
If there is a runtime exception, capture and then discard and + finally wrap-up processing, or add catch capture for further processing.
As for adding finally, it is a "clean-up" process that is carried out regardless of whether an exception is caught or not.
8. In try-catch-finally, if there is return in catch, will finally still execute it?
It will be executed, before return.
Note: it is not good to change the return value in finally, because if there is a finally code block, the return statement in try will not immediately return to the caller
Instead, record the return value and return its value to the caller after the finally code block has been executed, and then if the return value is modified in finally, the modified value will be returned.
Obviously, returning or modifying the return value in finally will cause a lot of trouble to the program. In C #, programmers are prevented from doing this by directly using compilation errors.
Warnings or errors can also be generated in Java by raising the syntax checking level of the compiler.
Example 1
Public static int getInt () {int a = 10; try {System.out.println (a / 0); a = 20;} catch (ArithmeticException e) {a = 30 / / when the program is executed here, it is not return a, but return 30. The return path has been formed / / but there is finally behind it, so continue to execute finally content, a = 40 / / come back here again, continue return 30, and after forming the return path, the a here is not a variable, / / but a constant 30, so the result is 30 return a } finally {a = 40;} return a;}
Implementation result: 30
Example 2
Public static int getInt () {int a = 10; try {System.out.println (a / 0); a = 20;} catch (ArithmeticException e) {a = 30; return a;} finally {a = 40 / / if return is in finally, a return path is formed again. / / since it can only be returned through 1 return, 40 return an is returned directly here;}}
Implementation result: 40
9. Class ExampleA inherits Exception, class ExampleB inherits ExampleA.
There is the following code snippet:
Try {throw new ExampleB ("B");} catch (ExampleA e) {System.out.println ("ExampleA");} catch (Exception e) {System.out.println ("Exception");}
What is the result of the implementation?
Output: ExampleA
Description: according to the principle of Richter substitution (where parent types can be used, child types must be used)
Grabbing catch blocks with ExampleA type exceptions can catch ExampleB type exceptions thrown in try blocks.
10. State the running result of the following code class AnnoyanceException extends Exception {} class SneezeException extends AnnoyanceException {} public class Test04 {public static void main (String [] args) throws Exception {try {try {throw new SneezeException ();} catch (AnnoyanceException a) {System.out.println ("Caught Annoyance"); throw a } catch (SneezeException s) {System.out.println ("Caught Sneeze"); return;} finally {System.out.println ("Hello World");}
Results:
Caught Annoyance
Caught Sneeze
Hello World
11. 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 BufferOverflowException exceptions for IO operations
12. 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.StackOverflowError: 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. This exception is thrown when the application attempts to use null where the object is required. 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.
13. The difference of Throwable, Error, Exception and RuntimeException in Java exception
The Throwable class is the superclass of all errors or exceptions in the Java language. Its two subclasses are Error and Exception
Error is a subclass of Throwable and is used to indicate serious problems that reasonable applications should not attempt to capture, such as memory overflows, virtual machine errors, stack overflows, and so on.
This kind of error is generally related to the hardware and has nothing to do with the program itself. It is usually handled by the system and cannot be captured and handled by the program itself.
OutOfMemoryError memory overflow
Java.lang.StackOverflowError stack overflow error, which is thrown when an application recursive call is too deep to cause a stack overflow
Exception class and its subclasses are a form of Throwable, reasonable conditions that the application wants to capture, and some exceptions are unpredictable when writing the program.
Such as interrupt exception, illegal access exception and so on. In order to ensure the robustness of the program, Java requires that these possible exceptions must be caught and handled.
The RuntimeException class is a subclass of the Exception class (a superclass of exceptions that may be thrown during the normal operation of the Java virtual machine)
The IOExeption class is a subclass of the Exception class.
Fourth, Java exception handling best practices
Handling exceptions in Java is not an easy task. Not only is it difficult for beginners to understand, even some experienced developers
It also takes a lot of time to think about how to handle exceptions, including which exceptions need to be handled, how to handle them, and so on.
This is why most development teams make rules to regulate exception handling. These specifications between teams are often very different.
This article presents several best practices for exception handling that are used by many teams.
1. Clean up resources in the finally block or use try-with-resource statements
When using a resource like InputStream that needs to be closed after use, a common mistake is to close the resource at the end of the try block.
Public static void readFile (String filePath) {BufferedReader reader = null; String res; try {reader = new BufferedReader (new FileReader (filePath)); while ((res = reader.readLine ())! = null) {System.out.println (res);} reader.close (); / / error! } catch (IOException e) {e.printStackTrace ();}}
The problem is that this code works only if no exception is thrown. The code within the try code block will execute normally
And the resource can be closed normally. However, try code blocks are used for a reason, and one or more methods that may throw an exception are generally called
Also, you may throw an exception yourself, which means that the code may not be executed to the last part of the try code block.
As a result, the resource is not closed. Therefore, you should put the clean-up code in finally, or use the try-with-resource feature.
(1) use finally code blocks
Unlike the previous lines of try code blocks, finally code blocks are always executed.
Executes regardless of whether the try code block is executed successfully or after the exception is handled in the catch code block.
Therefore, you can ensure that all open resources are cleaned up here.
Public static void readFile (String filePath) {BufferedReader reader = null; String res; try {reader = new BufferedReader (new FileReader (filePath)); while ((res = reader.readLine ())! = null) {System.out.println (res);}} catch (IOException e) {e.printStackTrace () } finally {if (null! = reader) {/ / correct try {reader.close ();} catch (IOException e) {e.printStackTrace ();} (2) try-with-resource syntax for Java 7
If your resource implements the AutoCloseable interface, you can use this syntax. Most Java standard resources inherit this interface.
When you open a resource in the try clause, the resource automatically closes after the execution of the try code block or after exception handling.
Public static void readFile (String filePath) {String res; try {BufferedReader reader = new BufferedReader (new FileReader (filePath)); while ((res = reader.readLine ())! = null) {System.out.println (res);}} catch (IOException e) {e.printStackTrace ();}} 2, priority exception
The more specific the exception you throw, the better. Always remember that your colleague, or you in a few months' time, will call your method and handle the exception.
Therefore, we need to ensure that they are provided with as much information as possible. This makes your API easier to understand.
The caller of your method can better handle exceptions and avoid additional checks. Therefore, always try to find the class of abnormal events that best suits you.
For example, throw a NumberFormatException to replace an IllegalArgumentException. Avoid throwing an ambiguous exception.
Public void doNotDoThis () throws Exception {} public void doThis () throws NumberFormatException {} 3, document the exception
Documentation is also required when declaring that an exception is thrown on a method. The aim is to provide as much information as possible to the caller
As a result, exceptions can be better avoided or handled. Add the @ throws declaration to Javadoc and describe the scenario in which an exception is thrown.
4. Use descriptive messages to throw an exception
When throwing an exception, you need to describe the problem and related information as accurately as possible, whether printed to the log or in the monitoring tool
Can be read more easily, so that you can better locate the specific error information, the severity of the error, and so on.
But this is not to talk at length about the error message, because the original class name of Exception can reflect the cause of the error, so you only need to describe it in one or two sentences.
If a specific exception is thrown, its class name probably already describes the error. So you don't need to provide a lot of extra information.
A good example is NumberFormatException. When you provide String in the wrong format, it will be thrown by the constructor of the java.lang.Long class.
Try {new Long ("xxx");} catch (NumberFormatException e) {e.printStackTrace ();}
Throw out
Java.lang.NumberFormatException: For input string: "xxx" at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) at java.lang.Long.parseLong (Long.java:589) at java.lang.Long. (Long.java:965) 5, give priority to catching the most specific exception
Most IDE can help you implement this best practice. When you try to catch less specific exceptions first, they report inaccessible blocks of code.
The problem, however, is that only the first catch block that matches the exception is executed.
Therefore, if you capture IllegalArgumentException first, you will never reach the catch block that should handle the more specific NumberFormatException
Because it is a subclass of IllegalArgumentException.
Always catch the most specific exception class first, and add less specific catch blocks to the end of the list.
Public static void catchMostSpecificExceptionFirst () {try {/ / do} catch (NumberFormatException e) {/ / handle NumberFormatException} catch (IllegalArgumentException e) {/ / handle IllegalArgumentException}} 6, do not capture the Throwable class
Throwable is the superclass of all exceptions and errors. You can use it in the catch clause, but you should never do it!
If you use Throwable in the catch clause, it catches not only all exceptions but also all errors.
JVM throws an error indicating a serious problem that should not be handled by the application.
A typical example is OutOfMemoryError or StackOverflowError.
Both are caused by situations outside the control of the application and cannot be handled. So, it's best not to capture Throwable.
Unless you are sure that you are in a special situation to deal with mistakes.
7. Don't ignore exceptions
In many cases, developers are confident that they won't throw exceptions, so they write a catch block without doing any processing or logging.
Public void doNotIgnoreExceptions () {try {/ / do} catch (NumberFormatException e) {/ / this will neverhappen}}
But the reality is that unexpected exceptions often occur, or it is impossible to determine whether the code here will be changed in the future (code that prevents exceptions from being thrown has been removed)
At this time, because the exception is caught, it is impossible to get enough error information to locate the problem. It makes sense to at least record abnormal information.
Public void logAnException () {try {/ / do} catch (NumberFormatException e) {log.error ("This should never happen:" + e)} 8, do not record and throw an exception
This is probably the most often overlooked best practice. You can find that a lot of code and even class libraries have logic to catch exceptions, log them, and throw them again.
Try {new Long ("xxx");} catch (NumberFormatException e) {log.error (e); throw e;}
This processing logic seems reasonable. But this often outputs multiple logs to the same exception.
There is no more useful information attached to the extra logs. If you want to provide more useful information, you can wrap the exception as a custom exception.
Public void wrapException (String input) throws MyException {try {/ / do} catch (NumberFormatException e) {throw new MyException ("A message that describesthe error.", e);}}
Therefore, catch the exception only when you want to handle it, otherwise you just need to declare it in the method signature and let the caller handle it.
9. Do not discard the original exception when the package is abnormal
It is a common practice to catch standard exceptions and wrap them as custom exceptions. In this way, more specific exception information can be added and exception handling can be done for it.
When you do this, be sure to set the original exception as the cause (note: refer to the original exception e in the code NumberFormatException e below).
The Exception class provides a special constructor method that accepts a Throwable as an argument.
Otherwise, you will lose the stack trace and the message of the original exception, which will make it difficult to analyze the exception event that caused the exception.
Public void wrapException (String input) throws MyException {try {/ / do} catch (NumberFormatException e) {throw new MyException ("A message that describesthe error.", e); / equivalent to / / MyException myException = new MyException ("A message that describesthe error."); / / myException.initCause (e); / / throw myException;}} 10, do not use exception control program flow
Exceptions should not be used to control the execution flow of the application, for example, if statements should be used for conditional judgment
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. Use the exceptions provided by Java API as much as possible in development.
If the standard exception does not meet your requirements, create your own custom exception. Use standard exceptions as much as possible to help new developers understand the project code.
12. Exceptions can affect performance
The performance cost of exception handling is very high, and every Java programmer should keep this in mind when developing.
Creating an exception is very slow, and throwing an exception consumes 1~5ms
When an exception is passed between multiple levels of the application, it will slow down the performance of the entire application.
Use exceptions only in exception cases
Use exceptions in recoverable exception cases
Although using exceptions is good for Java development, it's best not to capture too many call stacks in your application.
Because in many cases you don't need to print the call stack to know what went wrong.
Therefore, exception messages should provide the right information.
13. Summary
To sum up, there are many different situations to consider when you throw or catch an exception
And most of the things are about improving the readability of the code or the availability of 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.
Only in this way can team members understand these common concepts and use them at work.
This is the end of the summary of Java exception-related knowledge points. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.