当前位置:网站首页>Try catch finally implementation mechanism
Try catch finally implementation mechanism
2022-06-24 16:44:00 【Erossssssss】
try catch finally How to execute jump in case of exception ?finally Why statements must execute ?
The reasons behind it are worth investigating , We from JVM From the perspective of try catch finally The implementation principle behind this syntax .
JVM How to execute try - catch
Create a TryCatchFinallyDemo.java class , stay foo() Method try-catch block; The statement handleException This empty method .
Use javac The directive compiles it into class file , And use javap -c -v -s View results . Relative to no try-catch block Code for , There is one more in the following code Exception Table.
In the compiled bytecode , Each method comes with an exception table (Exception table), Each row in the exception table represents an exception handler , from from The pointer 、to The pointer 、target The pointer 、 The type of exception caught type form .
The values of these Pointers are bytecode indexes , Used to locate bytecode Its meaning is in [from, to) Bytecode range , An exception of type... Was thrown type It's abnormal , It will jump to target At the bytecode of .
such as , The above example exception table indicates : stay 0 To 3 middle ( It doesn't contain 3) If it throws Exception abnormal , Jump to 6 perform .
Multiple catch sentence
The following example has more than one catch Examples of statements , Although the following three exceptions will not occur .
Use javac -s You can simply see the corresponding ctach Piece of bytecode .Exception Table Three types of exceptions in , If [0,3) Code segment ( barring 3) Something goes wrong , You can jump to ,6,15,24 Line of code looks for the type of exception that can be caught .
When something goes wrong with the program ,Java The virtual opportunity traverses all the entries in the exception table from top to bottom . When the bytecode index value that triggers the exception is in the... Of an exception entry [from, to) Within the scope of , It will determine whether the exception thrown matches the exception that the entry wants to catch .
- If the match ,Java The virtual opportunity jumps the control flow to target Bytecode to ; If not, continue to traverse the exception table
- If you traverse all the exception tables , Not yet matched to exception handler , Then the The exception will spread to the caller (caller) Repeat the above operation in . In the worst case, the virtual machine needs to traverse the thread Java Exception table for all methods on the stack . If in all callers in the method stack , No matching exception table found ,JVM The current method stack will be cleared .
finally analysis
finally The secret of always executing
that ,JVM How to ensure finally Keywords are always executed ? We add one to the above example finally block.
Recompile and use javap -c see .
You can see , The bytecode contains three copies finally Sentence block , The program is normal return And exceptions throw Before . Two of them try and catch call return Before , One is the exception throw Before .
Java The method is replication finally The contents of the code block , We separate try catch All code blocks are normal return and abnormal throw Before . therefore finally Code blocks always execute .
Here are two scenarios that are not commonly used .
finally Modify the return value scenario
The following code runs and the result is 1, still 3 Well ? This scene can confuse many people . Let's execute on one side , The result is 1.
Compile and view bytecode :
By bytecode , We found that , stay try Of the statement return In block ,return The returned variables are not directly returned i value , It's execution finally Block before i Values are stored in the staging area , When executed return The value in the temporary area directly returned by , Even in finally In the statement, the variable i The value of has been modified , It does not affect the returned value .
finally There is return Scene
When finally There is return When the sentence is ,return Statement will rewrite try-block, catch-block The return value of .
Slightly modify the example in the previous chapter : stay finally Statement to add a line of return value . The result of the operation is 3, Back to finally block The value in .
View bytecode after compilation , And make a comparison with the examples in the previous chapter . On the left is the bytecode compiled from the previous chapter , On the right is the bytecode compiled by the above example .
Every try block, catch block Rear side ,return Before the order , Will be copied finally block Code block for . You can see , although try-catch block Medium i Values are temporarily stored , But because of finally Yes return sentence , Back again finally The modified i value .
summary
- First of all ,JVM Use exception table to handle try-catch Jump logic of ;
- second ,finally Is implemented by copying finally Statement block finally Semantic logic that must be executed ;
- Third , Explained in finally There is return Statements or Throw an abnormal situation .
边栏推荐
- Don't let [mana] destroy your code!
- Kubernetes characteristic research: sidecar containers
- Annual contribution! Tencent cloud middleware product upgrade conference is in hot registration!
- [tke] whether to configure SNAT when the container accesses services outside the node
- What is browser fingerprint recognition?
- 6 things all engineers should know before FEA
- A survey of training on graphs: taxonomy, methods, and Applications
- How to open a futures account safely? Which futures companies are more reliable?
- How to save data to the greatest extent after deleting LV by misoperation under AIX?
- 06. Tencent cloud IOT device side learning - Introduction to basic functions
猜你喜欢

Cognition and difference of service number, subscription number, applet and enterprise number (enterprise wechat)

A survey on dynamic neural networks for natural language processing, University of California

C. K-th not divisible by n (Mathematics + thinking) codeforces round 640 (Div. 4)

Applet - use of template
![[go] concurrent programming channel](/img/6a/d62678467bbc6dfb6a50ae42bacc96.jpg)
[go] concurrent programming channel

Some adventurer hybrid versions with potential safety hazards will be recalled
MySQL Advanced Series: locks - locks in InnoDB

A survey of training on graphs: taxonomy, methods, and Applications

A survey on model compression for natural language processing (NLP model compression overview)

Ui- first lesson
随机推荐
Inter thread communication of embedded development foundation
中金证券靠谱吗?是否合法?开股票账户安全吗?
Find out the invisible assets -- use hosts collision to break through the boundary
A memory leak caused by timeout scheduling of context and goroutine implementation
What can Lu yuanjiu Jiao buy?
Comparison of jmeter/k6/locust pressure measuring tools (not completed yet)
Percona Toolkit series - Pt deadlock logger
@There is a free copyright protection service for enterprises in Dawan District
Where is the most formal and safe account opening for speculation futures? How to open a futures account?
What is thermal data detection?
Enterprise service growth path (7): what key factors will affect SaaS' sales performance?
Cognition and difference of service number, subscription number, applet and enterprise number (enterprise wechat)
Regular expression learning artifact!
[tke] nodelocaldnschache is used in IPVS forwarding mode
Leetcode notes of Google boss | necessary for school recruitment!
What is cloud development? Why cloud development? Talk about our story
Interpretation of swin transformer source code
A survey of training on graphs: taxonomy, methods, and Applications
Cloud + community [play with Tencent cloud] video solicitation activity winners announced
Markdown syntax -- Formula