In practical development, some exceptions are often generated during compile time and must be handled. These exceptions are called compile-time exceptions, also called Checked exceptions.
Exceptions that are thrown during a program’s runtime and can be compiled without exception handling code are called runtime exceptions, also known as unchecked exceptions. Each of these exceptions is explained in detail.
Compile-time exceptions
Of the Exception subclasses, all but the RuntimeException class and its subclasses are compile-time exceptions. Compile-time exceptions are characterized by the Java compiler checking the code during program compilation. If obvious exceptions occur, the exceptions must be handled; otherwise, the program cannot be compiled. There are two ways to handle compile-time exceptions, as follows:
- Using a try… The catch statement catches exceptions.
- Throws exceptions are declared using the throws keyword for the caller to handle.
2. Runtime exception
The RuntimeException class and its subclasses are runtime exceptions. Runtime exceptions are automatically caught and handled by the Java Virtual machine while the program is running, even without using try… A catch statement catches or declares a throw using the throws keyword. The program can be compiled, but an error may be reported during execution.
In Java, there are several common runtime exceptions, as shown in the figure below.
Runtime exceptions are generally caused by logic errors in the program that cannot be recovered while the program is running. For example, a runtime exception will occur if the maximum array marker is exceeded when accessing an element of an array through the array’s markers:
int [ ] arr=new int[5];
System.out.println (arr[5]);
Copy the code
In the above code, since the length of the array ARR is 5, the maximum corner marker should be 4. When arR [5] is used to access elements in the array, an exception will occur that the array corner marker is out of bounds.
Java learning process will certainly encounter a variety of problems, I can share a set of Java video for you, I hope to help Java beginners and zero foundation friends less detour!
Recommended learning videos:
Java300: The new Java300 is coming! Java zero basic white self learning Java essential quality tutorial
Java zero Basic introduction to the full set of tutorials _ suitable for 0 basic introduction _JavaSE_Java basic tutorial
This is the most common type of exception in Java. Have you encountered any weird exceptions? You can discuss it in the comments!