Java common exceptions of Runtime Exception

  • 2020-05-10 18:05:50
  • OfStack

This article focuses on some of the concepts of the exception mechanism in Java. The purpose of this article is to make it easy for me to recall these things quickly if I forget them after a long time.

1. Abnormal mechanism

1.1 exception mechanism refers to how the program handles when an error occurs in the program. In particular, the exception mechanism provides a safe channel for the program to exit. When an error occurs, the flow of execution of the program changes and control of the program is transferred to the exception handler.

1.2 the traditional method to deal with exceptions is that a function returns a special result to indicate the occurrence of an exception (usually the special result is commonly known as the convention), and the program calling this function is responsible for checking and analyzing the result returned by the function. This has the following disadvantages: for example, if the function returns -1, it means there is an exception, but if the function does return the correct value of -1, there will be confusion. The readability is reduced, and the program code is mixed with the code to handle the exception in 1. Analyzing errors by the calling program requires a deep understanding of library functions by the client programmer.

1.3 process of exception handling

1.3.1 if an error is encountered, the method ends immediately and does not return a value; At the same time, an exception object is thrown

1.3.2 the program that calls this method will not continue to execute, but will search for an exception handler that can handle the exception and execute the code

2. Classification of anomalies

2.1 classification of anomalies

2.1.1 exception inheritance structure: base classes Throwable, Error and Exception inherit Throwable, RuntimeException and IOException inherit Exception, and RuntimeException inherit RuntimeException.

2.1.2 Error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).

2.2 characteristics of each type of exception

2.2.1 Error system the Error class system describes internal errors and resource depletion in the Java running system. Applications should not throw objects of this type (1 is generally thrown by the virtual machine). If this error occurs, there is nothing you can do except try to make the program exit safely. Therefore, in the process of programming, we should pay more attention to the Exception system.

2.2.2 Exception system Exception system includes RuntimeException system and other non-RuntimeException systems

2.2.2.1 the RuntimeException RuntimeException system includes incorrect type conversion, out-of-bounds access to arrays, and attempts to access null Pointers. The principle for handling RuntimeException is: if RuntimeException occurs, then 1 must be the programmer's fault. For example, you can avoid array out-of-bounds access exceptions by checking array subscripts and array boundaries.

2.2.2.2 other (IOException, etc.) exceptions like 1 are usually external errors, such as trying to read data from behind the end of a file, etc. This is not an error of the program itself, but an external error in the application environment.

2.3 differences in exception classification from C++

2.3.1 in fact, the name RuntimeException in Java is not appropriate, because any exception occurs at runtime. (an error at compile time is not an exception; in other words, an exception is an error at run time.)

2.3.2 logic_error in C++ is equivalent to RuntimeException in Java, while runtime_error is equivalent to RuntimeException type exceptions in Java.

3. Use of exceptions

3.1 declaration methods throw exceptions

3.1.1 grammar: throws

3.1.2 why declare methods to throw exceptions? Whether a method throws an exception is as important as the type of the method return value. Assuming that a method throws an exception without actually declaring that the method will throw an exception, the client programmer can call the method without writing code to handle the exception. Then, once an exception occurs, there is no appropriate exception controller to solve the exception.

3.1.3 why must the exception 1 thrown be a checked exception? RuntimeException and Error can be generated in any code. They do not need to be thrown as shown by the programmer. Once an error occurs, the corresponding exception will be thrown automatically. Just check that the exception is thrown by the programmer, which is divided into two cases: the client programmer calls the library function that will throw the exception (the exception of the library function is thrown by the library programmer); The client programmer throws the exception himself using the throw statement. When it comes to Error, programmer 1 is powerless. If RuntimeException is encountered, then 1 must be a logical error in the program and the program should be modified (equivalent to one method of debugging); Only checked exceptions are of concern to the programmer, and the program should and only should throw or handle checked exceptions.

3.1.4 note: covering the parent class a subclass of methods can't throw more unusual than the parent class method, so, sometimes when they design of the parent class method statement throws an exception, but the actual implementation of the code is not an exception is thrown, the aim is to facilitate the subclass method overrides the superclass method can throw an exception.

3.2 how to throw an exception

3.2.1 grammar: throw

3.2.2 what exception is thrown? For an exception object, the really useful information is the object type of the exception, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, the class name is the only useful information for 1. So, when choosing what exception to throw, the most important thing to do is to select the class name of the exception that explicitly states the condition of the exception.

3.2.3 there are usually two kinds of constructors for exception objects: one is a constructor without parameters; the other is a constructor without parameters. The other is a constructor with a string that will serve as an additional specification for the exception object in addition to the type name.

3.2.4 create your own exceptions: when none of Java's built-in exceptions can clearly explain the exception, you need to create your own exceptions. It is important to note that the only useful information for 1 is the type name, so don't spend any effort on the design of the exception class.

3.3 catch exceptions if an exception is not handled, then for a non-graphical interface program, the program will be terminated and output exception information; For a graphical interface program, abnormal information is also output, but the program does not stop, but returns to the user interface processing loop.

3.3.1 syntax: try, catch, and finally (omitted) controller modules must be immediately behind the try block. If an exception is thrown, the exception control mechanism searches for the first controller whose parameters match the type of exception and then it enters that catch clause, believing that the exception is under control. When catch clause ends the search for the controller stops.

3.3.1.1 catch multiple exceptions (note the syntax and the order of capture) (omitted)

3.3.1.2 usage of finally and exception handling process (omitted)

3.3.2 what does exception handling do? For Java, there is no need to recycle memory for exception handling due to garbage collection. However, there are still some resources that programmers need to collect, such as files, network connections, and images.

3.3.3 should you declare a method to throw an exception or catch an exception in a method? Principle: catch and handle what exceptions know how to handle, and pass what exceptions don't know how to handle

3.3.4 throw an exception again

3.3.4.1 why throw an exception again? At this level, only 1 part of the content can be processed, and some processing needs to be done at a higher level, so you should throw an exception again. This enables the exception handler at each level to handle the exceptions it can handle.

3.3.4.2 the exception handling process corresponding to the catch block with the same 1try block will be ignored, and the exception thrown will enter the higher level 1.

Other questions about exceptions

First of all, it's so easy to use exceptions that programmer 1 is no longer willing to write error-handling code and simply throw an exception. This is not the right thing to do; for perfectly known errors, you should write code that handles them to increase the robustness of your program. In addition, the exception mechanism is very inefficient.

4.2 distinguish exceptions from common errors for common completely 1-caused errors, code should be written to handle such errors to increase the robustness of the program. Exceptions are required only for external, undetermined and predictable runtime errors.

4.3 information contained in the exception object 1 in general, the only useful information of the exception object 1 is the type information. But when you use an unusual constructor with a string, that string can also be used as extra information. Calling the getMessage(), toString(), or printStackTrace() methods of the exception object gets additional information about the exception object, the class name, and the call stack, respectively. And the information contained in the last one is the superset of the first one.

Common exceptions:

Operations not supported by UnsupportedOperationException

IllegalArgumentException invalid parameter

The IndexOutOfBoundsException index is out of bounds

IllegalStateException illegal status

Exceptions are distinct from normal warnings, etc. When an exception occurs to an application, the normal flow of instructions to the executing program is interrupted. That is, the code behind the exception will not execute correctly. It even triggers a rollback of the database.

In the Java development platform, exceptions include both predefined and custom exceptions. The two types of exceptions complement each other. As a qualified program developer, be good at using exceptions in your application. This can improve the interactivity of the application. At the same time, it is a prerequisite to ensure the normal operation of the application. Therefore, exception handling is very important for developing a good application. For this reason, I believe that application developers should have an in-depth understanding of common exceptions in Java applications. You can handle custom exceptions only if you understand these common exceptions.

      1. Types and causes of common anomalies.

      for the common exceptions of Java application, the author believes that the program developer should understand from two aspects. 1 is to know what common Java application exceptions are, and 2 is to know what causes this exception. This not only requires the program manager to pay attention to accumulation in his daily work, but also to collect information from other sources if necessary. The author carries on an analysis to this, hope can have 1 definite help to you program developer.

      1, SQLException: operation database exception class.

      current Java applications are mostly database dependent. This class is triggered when an error occurs when the Java application communicates with the database. The database error message is also displayed to the user through this class. In other words, the operation database exception class is the bridge between the database and the user exception information transfer. For example, if the user now inserts data into the system, a field in the database must be unique to 1. When the user inserts data, if the value of this field is repeated with the existing record, violating the database's exclusivity constraint, the database will run out with an exception message. This information may not be visible to the user as it occurs at the database level. At this point, the operation database exception class catches the exception information of the database and passes the exception information to the foreground. This way, the foreground user can analyze the cause of the error based on the exception information. This is the main purpose of this operation database exception class. In the Java application, this class is triggered when all database operations occur in an exception. So at this point the Java application itself is often too general to say that there was an error interacting with the database. Instead, the database prompt is more useful.

      2, ClassCastException: data type conversion exception.

In Java applications, data types sometimes need to be converted. This conversion includes the explicit conversion and the implicit conversion. However you do this conversion, one of the first conditions must be met, which is data type compatibility. If this principle is violated during data conversion, a data type conversion exception is triggered. As now in the application, the developer needs to convert 1 character date data into date data that can be accepted by the database. At this time, the developer only needs to control the date data in the foreground application, and 1 will not be a problem. However, if the foreground application lacks control, for example, the user enters only the month, day, and no year information when entering the date. An exception occurs when the application performs a data type conversion. According to the author's experience, data type conversion exceptions cause one exception to occur more often in application development, and one exception to occur at a lower level. For the most part, you can force some control over the data types in the application window. That is, data type compatibility is guaranteed before data type conversion. In this case, it is not easy to cause data type conversion exceptions. In fields where only numeric types are allowed, you can set the user to not be allowed to enter characters other than numeric values. The exception handling mechanism, however, ensures that the application will not be run incorrectly. However, in the actual development, we still need to anticipate the causes of the errors as much as possible and try to avoid the occurrence of exceptions.

      3, NumberFormatException: exception thrown when a string is converted to a numeric type.

In the data type conversion process, if there is a problem in the character conversion process, a separate exception is used for this exception in the Java program, that is, NumberFormatException. For example, when the character data "123456" is converted to numeric data, it is allowed. However, if the character data contains non-numeric characters, such as 123#56, an exception occurs when the conversion to numeric is made. The system catches the exception and handles it.

There are many more common exception classes in Java applications. If the corresponding class exception is not found, some class exceptions are not allowed to access, the file has ended the exception, the file did not find the exception, the field did not find the exception, and so on. Any system developer can use this exception name to determine the type of the current exception. It's not bad, but a bad memory is not as good as a bad pen. The application developer ends up with a list of exceptions when necessary, especially if there are custom exceptions. In this way, whether the application finds a problem during debugging or receives a complaint from the user during running, the cause of the exception can be found by the exception name in a timely manner. In this way, the exception can be resolved in the shortest time and the normal operation of the application can be restored. This is a measure I've been using for years and it's been very effective.

      2. Practical advice on exception management.

      the Java application provides only one exception class for manipulating database exceptions. Therefore, the error messages of the Java application alone often do not help the application staff to eliminate the cause of the error. You can only name whether the exception was caused by an application error or a database error. To go one step further and specify the cause of the problem, it is best to specify the cause when defining the exception at the database level. For example, a foreground application may call a database function or procedure. At this point in the database function or procedures can be done to explain the specific reason for an exception. A field cannot be empty when another table is generated from a base table, and so on. After the exception information is explained, if a similar exception is encountered, the operation database exception class will return the database exception information to the foreground user. This will help users find the cause of the problem and correct it in the shortest possible time. Of course, this requires coordination between the Java programmer and the database designer.

Second, it is important to note that anomalies are not the norm. In other words, most anomalies can be eliminated by reasonable prediction and prevention of the premise. If the design to 4 operation, you can limit the front application window in the divisor field to enter a value of 0 means to eliminate the application may be run in the exception. However, this often requires application developers to have more work experience and more rigorous thinking logic. Although this is difficult to determine, the author believes that developers should make efforts in this area, and not always let the user as your test, let the user to discover the design of the application Bug. I believe that only some factors that are really beyond the programmer's control are allowed to throw an exception. If the application developer is aware of the error but still fails to notice it or take effective measures to prevent it, then I will not allow it.

ArithmeticException (exception with a divisor of 0), BufferOverflowException (buffer overflow exception), BufferUnderflowException (buffer underflow exception), IndexOutOfBoundsException (out of bounds exception), NullPointerException (null pointer exception), EmptyStackException (empty stack exception), IllegalArgumentException (invalid parameter exception), NegativeArraySizeException, NoSuchElementException, SecurityException, SystemException, UndeclaredThrowableException

            1. java.lang.NullPointerException

The exception is interpreted as "the program met a null pointer," which simply means that an uninitialized or nonexistent object was called, confusing the initialization of an array with the initialization of an array element. The initialization of an array allocates the required space to the array, and the initialized array, where the elements are not instantiated, is still empty, so each element needs to be initialized (if called)

2. java. lang ClassNotFoundException

The exception is interpreted as "the specified class does not exist".

3. java. lang ArithmeticException

The explanation for this exception is a "mathematical anomaly," which is what happens when you divide by zero.

4. java. lang ArrayIndexOutOfBoundsException

Anomaly interpretation is "array subscript crossing the line", are now mostly in the program to the operation of the array, so at the time of call array 1 need to carefully check and see if their call subscript beyond the scope of the array, 1 a, display (i.e., with constant when the subscript) directly call is not so easy to make such a mistake, but the implicit (subscript box variable representations) call will often make a mistake, one kind of situation, is a procedure defined in the length of the array is determined by some specific methods, is not a prior statement, this time, l'd better check the array length, lest appear this exception.

5. java. lang IllegalArgumentException

The explanation of this exception is "method parameter error", for example, g.setColor(int red,int green,int blue) three values in this method, if there are more than 255 will also appear this exception, so once 1 found this exception, we need to do is to quickly check whether there is an error in the parameter passing in the method call 1.

6. java. lang IllegalAccessException

This exception is interpreted as "no access" when the application calls a class but the current method does not have access to the class. Be aware of this exception if Package is used in the program
Exception, Java

            thanks for reading, hope to help you, thank you for your support of this site!


Related articles: