当前位置:网站首页>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 .
边栏推荐
- Leetcode notes of Google boss | necessary for school recruitment!
- [tke] troubleshooting tips for container problems
- Interpretation of swin transformer source code
- Where is the most formal and safe account opening for speculation futures? How to open a futures account?
- Transpose convolution explanation
- MySQL timestamp format conversion date format string
- Dismantle the industrial chain of synthetic rubber industry, and the supply chain may become a sharp weapon for breakthrough
- Some adventurer hybrid versions with potential safety hazards will be recalled
- Introduction to koa (IV) koa operation database
- Object store signature generation
猜你喜欢
![[go] concurrent programming channel](/img/6a/d62678467bbc6dfb6a50ae42bacc96.jpg)
[go] concurrent programming channel

Problems encountered in the work of product manager

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

Applet wxss

Daily algorithm & interview questions, 28 days of special training in large factories - the 15th day (string)
![[leetcode108] convert an ordered array into a binary search tree (medium order traversal)](/img/e1/0fac59a531040d74fd7531e2840eb5.jpg)
[leetcode108] convert an ordered array into a binary search tree (medium order traversal)

There are potential safety hazards Land Rover recalls some hybrid vehicles

C. K-th not divisible by n (Mathematics + thinking) codeforces round 640 (Div. 4)
Advanced programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization

Some adventurer hybrid versions with potential safety hazards will be recalled
随机推荐
Script design for automatic login and command return
API documents are simple and beautiful. It only needs three steps to open
How to use the national standard streaming media server to view the video stream of the surveillance camera? How to correctly use UDP and TCP protocols?
MySQL date timestamp conversion
AI video structured intelligent security platform easycvr realizes intelligent security monitoring scheme for procuratorate building
The RTSP video structured intelligent analysis platform easynvr stops calling the PTZ interface through the onvif protocol to troubleshoot the pending status
AI structured intelligent security video monitoring technology, supporting the protective umbrella of the reserve / wild animals
Kubernetes 1.20.5 setting up Sentinel
Edit distance (linear dp+ violence matching)
Pytorch transpose convolution
Talk about some good ways to participate in the project
How does easydss, an online classroom / online medical live on demand platform, separate audio and video data?
Customized Tile Map cut - based on Tencent map
[go] concurrent programming channel
A set of very good H3C and Tianrongxin Internet cutover scheme templates, with word document download
Applet wxss
There are potential safety hazards Land Rover recalls some hybrid vehicles
50 growers | closed door meeting of marketing circle of friends ス gathering Magic City thinking collision to help enterprise marketing growth
Experience and suggestions on cloud development database
Mathematics in machine learning -- point estimation (IV): maximum posteriori probability (map)