What is an exception? The so-called exceptions are some errors that may occur when the program is running, such as trying to open a file that does not exist at all. Exception handling will change the control flow of the program and give the program a chance to handle the error. Therefore, in this section we will take a preliminary look at anomalies.
Java uses the throw keyword to throw an instance of an Exception subclass to indicate that an exception has occurred.
For example: The Integer class in the java.lang package calls its class method public static int parseInt(String s) to convert a "numeric" format string, such as "123456", into int type data. However, when trying to convert the string When "dot123" is converted into a number, the code is as follows:
intnumber=Integer.parseInt(dot123);
The method parseInt() will use the throw keyword to throw a NumberFormatException object during execution, which means that a NumberFormatException exception occurs when the program is running.
Java allows you to declare exceptions that may occur during the method call when defining a method, that is, it allows exception objects to be thrown during the method call to terminate the continued execution of the current method.
The exception object can call the following methods to obtain or output information about the exception:
publicStringgetMessage();//Get the detailed information of the exception publicvoidprintStackTrace();//Get the stack trace output (enterprises generally do not allow the output of this item, you can get all the exception information) publicStringtoString();//Represent the above information in text form getCause ();//Get the exception reason