In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "detailed introduction of Java exception mechanism". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "the detailed introduction of Java exception mechanism"!
1. An overview of exceptions
1.1 what is an anomaly?
Exception: a program exception event caused by external problems occurs during the operation of the program, and the exception will interrupt the operation of the program. (in object-oriented programming languages such as Java) the exception itself is an object, and when an exception is generated, an exception object is generated. Note that exceptions are not errors in java, which are explained in the following classification of exceptions.
Take the chestnut in your life as an example to illustrate the abnormality. If you usually drive to work, you can usually come to the company on time, but today you encounter a special situation, that is, when you encounter highway construction. If you don't do anything, you may be late for work. This kind of "road construction" is an exception in the program, it is an external problem caused by the event, not your own problem. (digression: however, the boss doesn't care what caused you to be late. Anyway, you are late. )
1.2 how do I handle exceptions?
1.2.1 traditional exception handling
If you are now required to enter the divisor and divisor in the console, ask for quotient.
The traditional practice goes like this:
Public static void main (String [] args) {System.out.println ("Please enter a divisor:"); Scanner sc = new Scanner (System.in); if (sc.hasNextInt ()) {int num1 = sc.nextInt (); System.out.println ("Please enter a divisor:") If (sc.hasNextInt ()) {int num2 = sc.nextInt (); if (0 = = num2) {System.out.println ("Divisor cannot be 0!") ;} else {int r = num1 / num2; System.out.println ("r =" + r);}} else {System.out.println ("invalid divisor input!") }} else {/ / it is possible to enter the string System.out.println in the console ("invalid divisor input!");}}
As can be seen from the above example, for such a simple business requirement, the code has to be written so long, because there are many problems to consider, so writing the code will feel very tired, and there will be exceptions, and the program will be interrupted. I won't execute the rest of the code. Therefore, the Java programming language uses exception handling mechanisms to provide programs with the ability to handle exceptions.
1.2.2 exception handling for java
In Java, the process of exception handling:
This process is like when you encounter highway construction at work, you make a detour, avoid the construction section, and let you arrive at the company on time!
two。 Classification of anomalies
In Java, all exceptions have a common ancestor, Throwable (which can be thrown). Throwable specifies the commonality of any problems that can be transmitted through the Java application using the exception propagation mechanism in the code.
Throwable: there are two important subclasses: Exception (exception) and Error (error), both of which are important subclasses of Java exception handling, each containing large quantum classes.
Error (error): an error that the program cannot handle, indicating a serious problem in running the application. Most errors have nothing to do with the actions performed by the code writer and represent problems with the JVM (Java virtual machine) when the code is running. For example, a Java virtual machine running error (Virtual MachineError) occurs when the JVM no longer has the memory resources needed to continue the operation. When these exceptions occur, the Java virtual machine (JVM) generally chooses thread termination.
These errors indicate that the failure occurred in the virtual machine itself, or when the virtual machine attempted to execute the application, such as Java virtual machine running error (Virtual MachineError), class definition error (NoClassDefFoundError), and so on. These errors are untraceable because they are outside the control and processing power of the application, and the vast majority are conditions that are not allowed to occur while the program is running. For a well-designed application, even if an error does occur, you should not essentially try to deal with the exception caused by it. In Java, errors are described by a subclass of Error.
Exception: an exception that can be handled by the program itself. The Exception class has an important subclass, RuntimeException. The RuntimeException class and its subclasses represent errors raised by "common operations of JVM". For example, if you attempt to use a null object reference, a divisor of zero, or an array out of bounds, run-time exceptions (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException are thrown, respectively. Note: the difference between exceptions and errors: exceptions can be handled by the program itself, while errors cannot be handled. In general, Java exceptions (including Exception and Error) are divided into detectable exceptions (checked exceptions) and untraceable exceptions (unchecked exceptions).
Searchable exception (exception that the compiler requires that must be handled): a reasonable exception that can easily occur when a correct program is running. Although the detectable anomaly is an abnormal condition, its occurrence is predictable to a certain extent, and once this abnormal condition occurs, it must be dealt with in some way.
Except for RuntimeException and its subclasses, other Exception classes and their subclasses are detectable exceptions. The characteristic of this exception is that the Java compiler will check it, that is, when such an exception may occur in the program, either catch it with the try-catch statement or declare that it is thrown with the throws clause, otherwise the compilation will not pass.
Undetectable exceptions (exceptions that the compiler does not require mandatory handling): include runtime exceptions (RuntimeException and its subclasses) and errors (Error).
There are two types of Exception exceptions: run-time exceptions and non-run-time exceptions (compiler exceptions). These exceptions should be handled as much as possible in the program.
Runtime exceptions: all are RuntimeException class and its subclass exceptions, such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript out of bounds exception) and so on. These exceptions are not checked, and can be captured or not handled in the program. These exceptions are generally caused by program logic errors, and the program should avoid such exceptions as much as possible from a logical point of view. The characteristic of the runtime exception is that the Java compiler does not check it, that is, when such an exception may occur in the program, it will be compiled even if it is not caught with the try-catch statement or declared to be thrown with the throws clause.
Non-runtime exception (compiler exception): an exception other than RuntimeException that belongs to the Exception class and its subclasses in type. From the perspective of program syntax, it is an exception that must be handled, and if it is not handled, the program cannot be compiled and passed. For example, IOException, SQLException, and user-defined Exception exceptions are not customized to check for exceptions.
3. Exception handling mechanism
Through the explanation of the exception above, we should have a certain understanding of the exception now. Here's how exceptions are handled in java.
In java, objects are used to represent exceptions.
Java is through try-catch, try-catch-finally, try-catch-catch... Statement to handle exceptions.
3.1 try-catch
3.1.1 use of try-catch
The try {} code block is used to execute code that may have an exception, and the catch (name of the exception type exception object) {} code block is used to catch and handle the exception. Try {/ / snippet 1 / snippet 1 / snippet 2} catch (exception type e) {/ / snippet 4 handling exception
Demo that handles the division of two numbers in 1.2.1:
Public static void main (String [] args) {Scanner sc = new Scanner (System.in); try {System.out.println ("please enter a divisor:"); int num1=sc.nextInt (); System.out.println ("Please enter a divisor:"); int num2=sc.nextInt (); int result=num1/num2 } catch (Exception e) {System.out.println ("handle exceptions here!") ;} System.out.println ("Program ends");}
3.1.2 order of execution of try-catch
The first one: no exception is encountered, that is, normal execution
The second kind: match to exception
When the code in try {} encounters an exception, it will compare it with the exception in parentheses in catch (). If it encounters an exception, the exception that belongs to catch will execute the code in the catch block and let the code behind the try-catch block be executed later.
The third kind: no exception can be matched.
3.2try-catch-finally
The try {} code block is used to execute code that may have exceptions, and the catch {} code block is used to catch and handle exceptions.
The finally {} code block is the code used to recycle resources (close files, close databases, close pipes). The finally code block must exit normally regardless of whether there is an exception or not (the only case where the finally block does not execute is System.exit (0) jvm. )
3.1.1 order of execution of try-catch-finally
First: catch blocks do not have return statements
(1) No exception was encountered:
Code within the try block-- > code within the finally block-- > code after the finally block
(2) encounter an exception and match it to an exception:
Code within the try block-- > code within the catch block-- > code within the finally block-- > code after the finally block
Public class Test01 {public static void main (String [] args) {try {int aura 1ap0; System.out.println ("try");} catch (Exception e) {System.out.println ("catch");} finally {System.out.println ("finally");} System.out.println ("Program ends properly") }}
Results:
1 catch
2 finally
3 the normal operation of the program ends
(3) an exception is encountered but does not match the exception:
Code in try block-- > code in finally block-- > program interrupts operation
Public static void main (String [] args) {try {int axi1catch / will throw ArithmeticException System.out.println ("try");} catch (NullPointerException e) {System.out.println ("catch");} finally {System.out.println ("finally");} System.out.println ("Program ends normally");}
Results:
1 Exception in thread "main" finally2 java.lang.ArithmeticException: / by zero3 at Test1.Test01.main (Test01.java:8)
The second kind: catch block has return statement
(1) No abnormality
Code within the try block-- > code within the finally block-- > return statements within the try block
Public class Test01 {public static int test () {try {int astat2; System.out.println ("try"); return a;} catch (Exception e) {System.out.println ("catch"); return 0;} finally {System.out.println ("finally") }} public static void main (String [] args) {System.out.println (test ()); System.out.println ("Program ends normally");}}
Results:
1 try2 finally3 44 program ends normal operation
(2) encounter an exception and match it to an exception:
The execution sequence is shown in the figure:
Public class Test01 {public static int test () {try {int aplink 2); System.out.println ("try"); return a;} catch (Exception e) {System.out.println ("catch"); return 0;} finally {System.out.println ("finally") }} public static void main (String [] args) {System.out.println (test ()); System.out.println ("Program ends normally");}}
Results:
1 catch2 finally3 04 program ends normal operation
(3) an exception is encountered but does not match the exception:
Code in try block-- > code in finally block-- > program interrupts operation
Public class Test01 {public static int test () {try {int aplink 2); System.out.println ("try"); return a;} catch (NullPointerException e) {System.out.println ("catch"); return 0;} finally {System.out.println ("finally") }} public static void main (String [] args) {System.out.println (test ()); System.out.println ("Program ends normally");}}
Results:
FinallyException in thread "main" java.lang.ArithmeticException: / by zero at Test1.Test01.test (Test01.java:8) at Test1.Test01.main (Test01.java:19)
4. Declare exception
4.1 throws
When a developer defines a method, he knows in advance that an exception will occur when the method is called, but he doesn't know how to handle it, so he can declare the exception on the method. Indicates that an exception will occur during the call of the method, which should be handled by the caller.
Use throws to declare exceptions in java. A method can declare multiple exceptions, separated by the sign, written as follows:
1 public void test2 () throws IOException,RuntimeException {2 / / there is an exception code, 3} is not handled here
4.2 relationship between declared exceptions and method overloading
Declaring exceptions has nothing to do with method overloading.
4.3 the relationship between declaration exceptions and method rewriting
If the parent class method declares an exception (at check time or run time), the subclass method can fully follow the parent class exception or not declare the exception.
If the parent class method does not declare an exception, the subclass can declare either the exception or RuntimeException, but not the Exception.
If the parent class declares a run-time exception, the subclass can fully follow the parent exception or not declare the exception.
5. Throw an exception
When the system exception can not meet the development needs, the developer can throw the exception according to the need.
Throw is used to manually throw an exception.
If the exception has not been handled (that is, the statement such as try-catch is not used), the exception will be thrown to the caller all the way to the main function. If there is no handling in the main function and continues to throw the exception after the main function, it will be thrown to the jvm. Chestnuts are as follows:
Public class Test01 {public static void test1 () throws IOException,RuntimeException {/ / the code thrown with an exception is not handled here, for example: throw new Exception ("exception information") } public static void test2 () throws IOException,RuntimeException {test1 (); / / calls a method that throws an exception, and there is no handling} public static void main (String [] args) throws IOException,RuntimeException {test2 (); / / main calls a method that throws an exception, but there is no handling here}}
Note:
Developers can choose to throw check-time and run-time exceptions according to their own needs
6. Custom exception
When the exception type in JDK does not meet the needs of the program, you can customize the exception class.
Custom exception steps:
[1] determine the type of exception. Inherit Excepion or RuntimeException
[2] write a custom exception class and implement the construction method
[3] manually declare and throw an exception where the method needs it.
Public class myException extends Exception {public myException () {super ();} public myException (String message) {super (message);} / customize the method in the exception to meet your needs public void showInfo () {System.out.println (super.getMessage () + "@ Line:") }} at this point, I believe you have a deeper understanding of the "detailed introduction of Java exception mechanism". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.