当前位置:网站首页>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 .
边栏推荐
- Nonholonomic constrained robot
- AI structured intelligent security video monitoring technology, supporting the protective umbrella of the reserve / wild animals
- CDs view permission check
- Is Guotai Junan Futures safe? How to open a futures account? How to reduce the futures commission?
- Bypass kernel function pointer integrity check
- MySQL Advanced Series: Locks - Locks in InnoDB
- Regular expression learning artifact!
- What is zero trust? Three classes will show you how to understand him!
- Activeindex selection and redirection in the menu bar on the right of easycvs
- Tencent on the other hand, I was puzzled by the "horse race" problem
猜你喜欢

A survey of training on graphs: taxonomy, methods, and Applications
MySQL Advanced Series: Locks - Locks in InnoDB
MySQL Advanced Series: locks - locks in InnoDB

Applet wxss

Applet - use of template

Cognition and difference of service number, subscription number, applet and enterprise number (enterprise wechat)
Advanced programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization

A survey on dynamic neural networks for natural language processing, University of California
![[go] concurrent programming channel](/img/6a/d62678467bbc6dfb6a50ae42bacc96.jpg)
[go] concurrent programming channel

Problems encountered in the work of product manager
随机推荐
MySQL timestamp format conversion date format string
05. Tencent cloud IOT device side learning -- mqtt protocol client implementation
How to open a futures account safely? Which futures companies are more reliable?
Video structured intelligent analysis platform easycvr video recording plan function optimization / regularly delete expired videos
Batch BOM Bapi test
A solution for building live video based on open source real-time audio and video webrtc architecture
Enterprise service growth path (7): what key factors will affect SaaS' sales performance?
[tke] enable CPU static management strategy
Modern finite element analysis can easily achieve accurate results
An error is reported during SVN uploading -svn sqlite[s13]
A survey of training on graphs: taxonomy, methods, and Applications
Scuffle on China's low code development platform -- make it clear that low code
中金证券靠谱吗?是否合法?开股票账户安全吗?
Heavy release! Tencent cloud ASW workflow, visual orchestration cloud service
Cognition and difference of service number, subscription number, applet and enterprise number (enterprise wechat)
Pageadmin CMS solution for redundant attachments in website construction
Advanced programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization
Fastjson vulnerability utilization techniques
What is a server
Is Shanjin futures safe? What are the procedures for opening futures accounts? How to reduce the futures commission?