In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
It is believed that many inexperienced people are at a loss about what is abnormal cognition and use in Java. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
I. the background of the anomaly.
We have come into contact with some "exceptions" in our code. For example
Divided by 0
Public static void main (String [] args) {System.out.println (10 / 0);}
Arithmetic exception:
Array subscript out of bounds
Array out of bounds
Int [] arr = {1,2,3}; System.out.println (arr [100]); / / Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100 accesses the null object
Null pointer exception
Public class Test {public int num = 10; public static void main (String [] args) {Test t = null; System.out.println (t.num);}} / / there are two types of Exception in thread "main" java.lang.NullPointerException exceptions:
Runtime exception (non-checked exception)
Arithmetic exception array out of bounds exception null pointer exception is an exception that occurs during the operation of the program
Compile-time exception (checked exception)
For example, using the clone method to draw a red line before compilation is a compile-time exception.
Abnormal system:
Let's take a look at null pointer exceptions (it's actually a class that inherits runtime exceptions)
Corresponding to the picture above.
Take a look at the runtime exception: inherit Exception (also see the figure above)
Take a look at Exception inheriting from Throwable:
From this graph, we come to the conclusion that each exception is a class, and the relationship between exceptions refers to the inheritance on the graph.
Let's take a look at Error
This is called a mistake.
The difference between exceptions and errors:
Errors: logic errors must be handled by the programmer
Exception: OK the exception. Let's move on.
Defensive programming:
Errors exist objectively in the code. So we should let the programmer know when there is something wrong with the program. We have two main ways.
LBYL: Look Before You Leap. Make a full inspection before the operation.
EAFP: It's Easier to Ask Forgiveness than Permission. It is easier to get forgiveness afterwards than to get permission beforehand. That is, operate first and deal with problems later.
Attention! Never memorize the above two concepts!
In fact, it's easy to understand. Give me a chestnut.
For example, when Lao Shi was young, he and your wife just began to talk about their partners. As we all know, talking to someone requires some intimate movements, such as "holding hands." Here comes the problem of emmmmm. There are two ways for Lao Shi to pull his wife's little hand:
A) Lao Shi said, Sister, can I hold your little hand? After getting the girl's consent, hold hands (this is LBYL).
B) when the old wet girl is not prepared, pull it directly. The big deal is that the girl gets angry and slaps Lao Shi, and Lao Shi apologizes again (this is EAFP).
The core idea of the exception is EAFP.
Exceptional benefits
For example, let's use pseudo code to demonstrate the process of starting a game with Arena of Valor.
LBYL style code (no exception) 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 selecting hero error; return;} ret = loading game screen (); if (! ret) {handling game loading error; return;} EAFP style code (using exception) 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;}
Comparing two different styles of code, we can find that in the first way, the code of normal flow and error handling flow are mixed together, and the code as a whole is chaotic. In the second way, the normal flow and error flow are separated, which makes it easier to understand the code.
Basic usage of exception basic grammar
The try code block contains code that may have an exception.
What is placed in the catch code block is the handling behavior after an exception occurs.
The code in the finally code block is used to deal with the aftermath and is executed at the end.
Both catch and finally can be added or not added according to the situation.
Code:
Public static void main (String [] args) {int [] arr = {1,2,3}; System.out.println ("before"); System.out.println (arr [100]); System.out.println ("after");}
Explanation:
We found that once an exception occurred, the program was terminated. After did not output correctly
Why?
When no exception is handled, once the exception occurs in the program, the exception will be handed over to jvm, and if the exception is handled for jvm, the program will certainly terminate.
Let's handle the exception ourselves: catch must catch the corresponding exception (if it is not caught, it will be handed over to JVM)
Results:
But the following will not be carried out.
Compared to the above, we handled the exception so that the program can continue to run.
There is no abnormal message on it. What can we do if we still want some tips?
Use: e.printStackTrace (); after still comes out normally
This scarlet letter can be used for reference.
The code sample catch can have more than one:
A piece of code may throw a variety of different exceptions, different exceptions have different ways of handling. Therefore, it can be matched with multiple catch code blocks.
If multiple exceptions are handled in exactly the same way, it can also be written like this
Code examples can also catch all exceptions with a single catch (not recommended)
Int [] arr = {1,2,3}; try {System.out.println ("before"); arr = null; System.out.println (arr [100]); System.out.println ("after");} catch (Exception e) {e.printStackTrace ();} System.out.println ("after try catch")
Why is it not recommended? because the scope of exception is too large to troubleshoot.
No condition is required for the execution of the code sample finally
Int [] arr = {1,2,3}; try {System.out.println ("before"); arr = null; System.out.println (arr [100]); System.out.println ("after");} catch (Exception e) {e.printStackTrace ();} finally {System.out.println ("finally code");}
Finally will be executed at last with or without exception.
The code sample uses try to recycle resources
Scanner.close () can release resources and can be written to finally or directly to try.
Try (Scanner sc = new Scanner (System.in)) {int num = sc.nextInt (); System.out.println ("num =" + num);} catch (Exception e) {e.printStackTrace ();}
If the code example is passed upwards without a proper way to handle the exception, it will eventually be handed over to JVM and the program will terminate abnormally (the same as when we didn't use try catch at first).
Public static void main (String [] args) {try {func ();} catch (ArrayIndexOutOfBoundsException e) {e.printStackTrace ();} System.out.println ("after try catch");} public static void func () {int [] arr = {1,2,3}; System.out.println (arr [100]) } / / Direct result java.lang.ArrayIndexOutOfBoundsException: 100at demo02.Test.func (Test.java:18) at demo02.Test.main (Test.java:9) after try catch
You can see that the above code is func, which can have exceptions, but is handled in the main method.
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.
About the handling of exceptions
There are many kinds of exceptions, which we have to decide according to different business scenarios.
For more serious problems (such as scenarios related to money counting), the program should be allowed to crash directly to prevent more serious consequences.
For less serious problems (most scenarios), you can record the error log and notify the programmer in time through the monitoring alarm program
For problems that may recover (network-related scenarios), you can try to retry.
The second simplified approach is taken in our current code. The error log we record is the abnormal method call information, which can be quickly
Quickly let us find the location of the anomaly. In the future, we will adopt a more complete way to record abnormal information in practical work.
Throw an exception
In addition to throwing exceptions from Java's built-in classes, programmers can also throw an exception manually. Use the throw keyword to do this
Public static void main (String [] args) {System.out.println (divide (10,0));} public static int divide (int x, int y) {if (y = = 0) {throw new ArithmeticException ("throw an exception divided by 0");} return x / y;} / / execution result Exception in thread "main" java.lang.ArithmeticException: at demo02.Test.divide (Test.java:14) at demo02.Test.main (Test.java:9)
In this code, we can throw the desired exception according to the actual situation. Some descriptive information can be specified at the same time when constructing exception objects.
Exception description
When dealing with exceptions, we usually want to know what possible exceptions will occur in this code.
We can use the throws keyword to explicitly mark the exceptions that may be thrown at the location defined by the method. This reminds the caller to pay attention to catching these exceptions.
Public static int divide (int x, int y) throws ArithmeticException {if (y = = 0) {throw new ArithmeticException ("divide by 0 exception");} return x / y;} III. Custom exception class
Although there are plenty of exception classes built into Java, there may be some situations in our actual scenario that require us to extend exception classes to create exceptions that conform to our actual situation.
Let's first take a look at what the other exceptions are like:
A null pointer exception inherits a run-time exception, but there are not many methods written in it, that is, two constructors of the parent class, so we can write our own exception according to it.
Create an exception class:
Use:
Results:
This is one of our custom exceptions.
So can we inherit Exception?
It is found that the report is wrong here. Why? Let's take a look at the exception architecture.
At this time, the compiler does not know whether it is a compile-time exception or a run-time exception, so it defaults to the compile-time exception with low permissions. At this time, we have to throw an exception.
The one above is not wrong. The following one begins? Why? Because we throw a compile-time exception, we need to try catch:
So this is a custom exception.
Let me give you an example:
For example, we implement a user login function: (if the user name is wrong to handle the user name error, the password error handles the password error)
At this point, we may need to throw two exceptions when dealing with user name and password errors. We can extend (inherit) existing exception classes to create exception classes related to our business.
A self-written class
We can write this in login:
Main method:
This is to use our own exceptions.
Note:
Custom exceptions usually inherit from Exception or RuntimeException
Exceptions inherited from Exception are checked by default
An exception inherited from RuntimeException defaults to an unchecked exception.
After reading the above, have you mastered what is the abnormal cognition and use methods in Java? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.