In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shares with you the content of a sample analysis of the Java exception handling mechanism. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Initial recognition of anomalies
We all encounter large and small exceptions more or less when writing code, such as:
Public class Test {public static void main (String [] args) {int [] arr = {1 arr [5]); System.out.println (arr [5]);}}
When our array is out of bounds, the compiler will tell us that the array is out of bounds and indicate which line has gone wrong.
Another example is:
Class Test {int num = 10; public static void main (String [] args) {Test test = null; System.out.println (test.num);}}
When we try to use a null object, the compiler also reports a null pointer exception:
So what exactly is an anomaly?
An exception is a mechanism that notifies the caller when an error occurs at run time.
Keyword "runtime", some errors are like this, such as misspelling System.out.println and writing
System.out.println. At this point, there will be an error in the compilation process, which is a compile-time error.
The runtime refers to the errors occurred in the process of JVM execution after the program has been compiled to get the class file.
two。 The basic usage of exceptions
Java exception handling depends on five keywords: try, catch, finally, throws, and throw. Let's introduce them one by one.
① try:try blocks are mainly placed in blocks of code that may generate exceptions. If there is a difference when executing the business logic code in the try block
Often, the system automatically generates an exception object, which is submitted to the runtime, a process called throwing
(throw) exception. When the Java environment receives an exception object, it looks for the appropriate catch block (either in this method or by the caller
Law).
② catch: the catch code block contains the handling behavior after an exception occurs. You can also write down the cause of the error or type
An error message on the stack. However, the catch statement cannot be empty, because once the catch statement is written empty, it means that the
Abnormal. Such as:
Empty catch blocks will prevent the exception from achieving its intended purpose, that is, forcing you to handle the exception situation. Ignoring exceptions is like ignoring
The fire signal is the same-if the fire signal is turned off, no one can see the fire signal when the real fire breaks out.
Yes. Maybe you will get away with it, or the result will be catastrophic. Whenever we see an empty catch block, we should
The alarm bell kept ringing.
Of course, there is also a situation where exceptions can be ignored, that is, when fileinputstream (read and write local files) is turned off. Because you're still
The state of the file has not been changed, so there is no need to perform any recovery action, and the required letter has been read from the file
Information, so it is not necessary to terminate the operation in progress.
The code in the ③ finally:finally code block is used to deal with the aftermath, will be executed at the end, and will certainly be executed. When encounter
When code such as return or throw in try or catch terminates the current method, jvm first executes the language in finally
Sentence, when the statement in finally has been executed, it will return to execute the return,throw statement in try/catch. If
If there is return or throw in finally, these statements will be executed, not the return or throw language in try/catch
Sentence. Code such as closing resources is generally written in finally blocks. But we don't usually add return to the finally statement.
Statement because it overrides the return statement executed in try. For example:
Finally overwrites the return 10 executed by the last try, and the final result returns 20. 0.
④ throws: in the signature of a method, it is used to throw an exception in this method to the caller, who can choose to catch or
Throw, if all methods (including main) choose to throw (or there is no appropriate way to handle exceptions, that is, the exception class
Type mismatch) then it will eventually be thrown to JVM, just as we did not use try and catch statements before. JVM print out
Stack locus (exception chain).
⑤ throw: used to throw a specific exception object. Commonly used in custom exception classes.
Ps:
With regard to "call stack", there is a mutual call relationship between methods, which can be described by "call stack".
There is a piece of memory space in JVM called virtual machine stack to store the call relationship between methods. When an exception occurs in the code
We can use e.printStackTrace () to view the call stack where the exception code occurs, which is usually written in the catch statement.
Exception handling flow
The program executes the code in try first.
If there is an exception in the code in try, it ends the code in try to see if it matches the exception type in catch.
If a matching exception type is found, the code in catch is executed
If no matching exception type is found, the exception is passed up to the upper caller.
Whether a matching exception type is found or not, the code in finally is executed (before the end of the method).
If the upper-level caller does not handle the exception, it continues to pass upward.
Until the main method does not have the appropriate code to handle the exception, it will be handed over to JVM to handle it, and the program will terminate abnormally.
3. Why use exceptions?
Existence is reasonable, for example
/ do not use exception int [] arr = {1,2,3}; System.out.println ("before"); System.out.println (arr [100]); System.out.println ("after")
When we do not use exceptions, we find that the exception program crashes directly, and the subsequent after is not printed.
/ use exception int [] arr = {1,2,3}; try {System.out.println ("before"); System.out.println (arr [100]); System.out.println ("after");} catch (ArrayIndexOutOfBoundsException e) {/ / print call stack e.printStackTrace () with exception } System.out.println ("after try catch")
When we use an exception, although the after is not executed, the program does not crash directly, and the following sout statement is executed
Isn't that what anomalies do?
For another example, when playing Arena of Valor, the network is suddenly cut off, he will not let your program crash directly, but will give you a chance to disconnect and reconnect:
Let's demonstrate the match process of Arena of Valor with pseudo code:
Do not use exception handling boolean ret = false; ret = login game (); if (! ret) {handle login game error; return;} ret = start matching (); if (! ret) {handle match error; return;} ret = game confirmation (); if (! ret) {handle game confirmation error; return;} ret = select hero (); if (! ret) {handle selection hero error; return } ret = load game screen (); if (! ret) {handle loading game errors; return;}. Use exception handling try {login game (); start matching (); game confirmation (); select hero (); load game screen ();.} catch (login game exception) {handle login game exception;} catch (start match exception) {handle start match exception;} catch (game confirmation exception) {handle game confirmation exception } catch (Select Hero exception) {handle Select Hero exception;} catch (load Game screen exception) {handle load Game screen exception;}.
We can clearly see that when the exception is not used, the correct flow is mixed with the error handling code, which is not easy to distinguish.
After an exception, it is easier to understand the code.
Of course, the benefits of using exceptions are much more than that. We can add information reminders to try and catch statements, such as you.
Developed a software, when that software is abnormal, send a message to remind you to fix it in time. The blogger made a small one.
Small QQ Mail information reminder function, the source code is in the code cloud, those who are interested can go and have a look! Need to configure QQ Mail pop3 server
Business, friends can check how to open ah, our theme is not this, so do not teach how to open. Show me:
Don't send mass messages, or you may be blocked.
Exceptions should only be used in the case of exceptions try {int I = 0; while (true) System.out.println (a [I + +]);} catch (ArrayIndexOutOfBoundsException e) {}
What is the use of this code? It doesn't seem obvious at all, which is why it's not really used. As it turns out, as
An implementation that traverses array elements is poorly conceived. When this loop attempts to access the array
For the first array element outside the boundary, throw (throw), capture (catch),
Ignore (ArrayIndexOutOfBoundsException) means to achieve the purpose of terminating the infinite cycle. Suppose it has something to do with numbers.
Group loops are equivalent, and for any Java programmer, the following standard pattern makes sense at a glance:
For (int m: a) System.out.println (m)
Why give priority to abnormal patterns over well-established standard ones?
May have been misled to use exception mechanisms to improve performance, because every time jvm accesses the array, it needs to determine whether the subscript is over.
They think that the end of the loop is hidden, but it is still visible in the foreach loop, which is undoubtedly superfluous and should be avoided
No.
There are three mistakes in the above idea:
1. Exception mechanisms are designed to handle abnormal situations, so JVM rarely optimizes them.
two。 The code is placed in try... Instead, catch blocks certain optimizations that jvm itself is going to perform.
3. The standard mode of traversing an array does not result in a redundancy check.
The lesson of this example is simple: as the name implies, exceptions should only be used in exceptional cases, and they should never be used in normal cases.
The control flow of.
Summary: exceptions are designed for use in exception situations and should not be used in general control statements.
4. Types of exceptions
Three types of thrown structures are provided in Java: checked exception (checked exception), run-time exception (run-time exception), and error (error).
(supplementary)
4.1 abnormality checked
What is the abnormality being checked? Any exception class that is not derived from error or runtime is an checked exception. For example:
We customize two exception classes and an interface, and a test class
Interface IUser {void changePwd () throws SafeException,RejectException;} class SafeException extends Exception {/ / because it inherits execption, so it is the checked exception class public SafeException () {} public SafeException (String message) {super (message);}} class RejectException extends Exception {/ / because it inherits execption, so it is the checked exception class public RejectException () {} public RejectException (String message) {super (message) }} public class Test {public static void main (String [] args) {IUser user = null; user.changePwd ();}}
We found that there was an error in the use of user in the test test class, because java thought that checked exceptions could be recompiled.
Section, so it forces the program to handle all checked exceptions, and the java program must explicitly place the checked
Exception, if the program does not handle it, an error occurs at compile time and cannot pass the compilation.
Solution:
① try, catch package
IUser user = null; try {user.changePwd ();} catch (SafeException e) {e.printStackTrace ();} catch (RejectException e) {e.printStackTrace ();}
② throws an exception and gives the handling action to the superior caller, who still has to write try and catch when calling this method.
Wrap the statement, so this is actually the equivalent of a declaration to let the caller know that the function needs to throw an exception
Public static void main (String [args) throws SafeException, RejectException {IUser user = null; user.changePwd ();}
4.2 unchecked anomalies
All exception classes that derive from error or runtime classes are unchecked exceptions.
It can be said that most of the exceptions we encounter in writing programs are unchecked exceptions, and the program crashes directly.
No execution.
Such as null pointer exception, array out of bounds exception, arithmetic exception, and so on, are all unchecked anomalies. It is checked out for you by the compiler runtime.
So it is also called a runtime exception.
5. How to use exceptions to avoid unnecessary use of checked exceptions
If the exception condition cannot be prevented, and once an exception occurs, the programmer can immediately take useful action, which is
It is advisable to be checked for anomalies. Otherwise, it is more suitable to use unchecked anomalies. This kind of example is
CloneNotSuppportedException (abnormal checked). It was thrown by Object.clone, Object.clone.
It can only be called on an object that implements Cloneable.
A checked exception thrown by a method alone can impose a very high additional burden on the programmer, if the method still has its
His checked exception, then it must have appeared in a try block when it is called, so this exception only needs another
Catch block. But when only one checked exception is thrown, only one exception causes the method to be in the try block, which is also
As a result, classes that use this method have to use try and catch statements, making the code less readable.
The checked exception makes the interface declaration fragile, for example, there is only one declared exception for an interface at the beginning.
InterfaceUser {/ / modify the user name and throw a security exception publicvoid changePassword () throws MySecurityExcepiton;}
However, with the development of the system, more and more classes implement the interface, and suddenly I find that changePassword needs to throw another difference.
Often, then all classes that implement this interface also have to add handling to this new exception, which is a large amount of work.
Summary: if it is not necessary, try to use non-checked anomalies, or change the checked anomalies into unchecked anomalies.
6. Custom exception
We use custom exceptions to implement a login error reporting applet.
Class NameException extends RuntimeException {/ / username error exception public NameException (String message) {super (message);}} class PasswordException extends RuntimeException {/ / password error exception public PasswordException (String message) {super (message);}}
Test class to test the run
Public class Test {private static final String name = "bit"; private static final String password = "123"; public static void Login (String name,String password) throws NameException,PasswordException {try {if (! Test.name.equals (name)) {throw new NameException (" user name error! ") ;} catch (NameException e) {e.printStackTrace ();} try {if (! Test.password.equals (password)) {throw new PasswordException ("password error");} catch (PasswordException e) {e.printStackTrace () }} public static void main (String [] args) {Scanner scanner = new Scanner (System.in); String name = scanner.nextLine (); String password = scanner.nextLine (); Login (name,password);}}
This is the end of the anomaly, why do you still feel a little bit unfinished?
Thank you for reading! This is the end of this article on "sample analysis of Java exception handling mechanism". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.