This article is participating in the “Digitalstar Project” to win a creative gift package and challenge the creative incentive money.
🍅 author’s home page: Java Li Yangyong public account to get fans exclusive java10G gift package
Many events do not always develop smoothly according to people’s own design wishes, and there are often abnormal situations. For example: You plan a weekend outing. Plan to go from home to destination to swimming to barbecue to home. When you are preparing for the barbecue, it suddenly rains heavily and you have to stop the outing and go home early. “Heavy rain” is an anomaly, and your plan should allow for it and have a plan for dealing with it. Computer programs also need to be written with these exceptions in mind. An exception is an exception generated when a program is running. It has become one of the criteria to measure the maturity of a language. The current mainstream programming language Java also provides exception handling mechanisms.
Introduction of abnormal
An exception in Java, also known as an exception, is an event that occurs during the execution of a program and interrupts the normal instruction flow of the executing program. To be able to handle runtime errors in a program in a timely and efficient manner, you must use exception classes, which make your program extremely fault-tolerant and more robust. There are three main reasons for an exception in Java:
- An internal Java error occurs and an exception occurs on the Java VIRTUAL machine.
- Exceptions caused by errors in written program code, such as null pointer exceptions, out-of-bounds array exceptions, etc.
- An exception manually generated by a throw statement, typically used to tell the caller of the method some necessary information.
Java handles exceptions through an object-oriented approach. During the execution of a method, if an exception occurs, the method generates an object representing the exception and passes it to the runtime system, which looks for code to handle the exception. We call the process of generating an exception object and submitting it to the runtime system a throw exception. The runtime system searches the method’s call stack until it finds an object that can handle that type of exception, a process called catching exceptions.
Case 1
To better understand what an exception is, let’s look at a very simple Java program. The following code implements an implementation that allows the user to enter integers between 1 and 3, otherwise prompting an error.
package io.renren.config; import java.util.Scanner; /** * Created by LiYangYong */ public class TestException { public static void main(String[] args) { System.out.println(" please enter your choice :(integer between 1 and 3) "); Scanner input = new Scanner(System.in); int num = input.nextInt(); switch (num) { case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; case 3: System.out.println("three"); break; default: System.out.println("error"); break; }}}Copy the code
Normally, the user will enter a number ranging from 1 to 3 as prompted. However, if the user does not enter as required, such as a letter, the program will run with an exception, as shown below.
Please enter your choice: (an integer between 1 ~ 3) 223 SDF Exception in the thread "is the main" Java. Util. InputMismatchException ats java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at io.renren.config.TestException.main(TestException.java:11) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Process finished with exit code 1Copy the code
Exception types
Java introduces exception classes specifically to handle runtime errors in programs in a timely and efficient manner. All exception types in Java are subclasses of the built-in java.lang.Throwable class, meaning that Throwable is at the top of the exception class hierarchy. The Throwable class has two Exception branches, Exception and Error, as shown in Figure 1.
As you can see from Figure 2, the Throwable class is the superclass for all exceptions and errors, with Error and Exception subclasses below representing errors and exceptions, respectively. The Exception class Exception is classified into runtime Exception and non-runtime Exception. These two types of exceptions are largely different, and are also called Unchecked Exception and Checked Exception.
- The Exception class is used for exceptions that may occur in user programs, and it is also used to create custom Exception type classes.
- Error defines exceptions that are not expected to be caught by the program under normal circumstances. This generally refers to JVM errors such as stack overflows.
This section does not discuss exception handling of the Error type, because they are usually catastrophic and fatal errors beyond the control of a program. Next, we’ll discuss Exception handling of the Exception type. Runtime exceptions are RuntimeException class and its subclasses abnormalities, such as NullPointerException, IndexOutOfBoundsException, these exceptions are not checked exception, in the program can choose to capture processing, also can not deal with. These exceptions are usually caused by program logic errors and should be logically avoided as much as possible. Non-runtime exceptions are exceptions other than RuntimeException and are of type to the Exception class and its subclasses. An exception that must be handled syntactically. If not handled, the program will fail to compile. Such as IOException, ClassNotFoundException, and user-defined Exception exceptions (generally, custom check exceptions are not allowed). Table 1 and Table 2 list the types and roles of runtime and non-runtime exceptions defined in Java.lang, respectively.
Exception types | instructions |
---|---|
ArithmeticException | Arithmetic error exceptions, such as dividing by zero |
ArraylndexOutOfBoundException | The array index is out of bounds |
ArrayStoreException | Assign to an array element whose type is incompatible |
ClassCastException | Type conversion exception |
IllegalArgumentException | Calling a method with an invalid argument |
lIIegalStateException | The environment or application is in an incorrect state |
lIIegalThreadStateException | The requested action is incompatible with the current thread state |
IndexOutOfBoundsException | Some type of index is out of bounds |
NullPointerException | An attempt was made to access a null object member. The null pointer is abnormal |
NegativeArraySizeException | An array created in the negative range |
NumberFormatException | Number conversion format exception, such as invalid string to float conversion |
TypeNotPresentException | Type not found |
Exception types | instructions |
---|---|
ClassNotFoundException | Class not found |
IllegalAccessException | The access class was denied |
InstantiationException | An object that attempts to create an abstract class or interface |
InterruptedException | A thread is interrupted by another thread |
NoSuchFieldException | The requested domain does not exist |
NoSuchMethodException | The requested method does not exist |
ReflectiveOperationException | A superclass of exceptions related to reflection |
Well, that’s it for today. I’m Obama. See you next time
Clocked articles updated 76/100 days