简体   繁体   English

Java Try-Catch - 它是如何执行的?

[英]Java Try-Catch - how does it execute?

I am just wondering what the Java VM does with a Try-Catch. 我只是想知道Java VM使用Try-Catch做了什么。 How does it execute it? 它是如何执行的?

My best guess is that it is like a Linux system which when installing something does a test run and if no errors are found asks the user if he/she wants to proceed. 我最好的猜测是,它就像一个Linux系统,在安装某些东西时会进行测试运行,如果没有发现错误,则会询问用户是否要继续。 In the case of a Try-Catch does it do a test run and if all is OK implement it? 在Try-Catch的情况下,它是否进行了测试运行,如果一切正常,那么实现它吗?

try
{
//execute your code
}catch(Exception e)
{
//Log message 
//IF you don't want to continue with the logic inside method, rethrow here.
}finally{
 //Ir-respective of what the status is in above cases, execute this code.
}
//Continue with other logic in the method

.This is useful in cases where you want to determine part of your code need to be executed (or) not in exception case. 。如果您想确定部分代码需要执行(或者不是异常情况),这非常有用。

To understand more about how try-catch works in java read this tutorial . 要了解有关try-catch如何在java中工作的更多信息,请阅读本教程

It is much simpler than that - if any clause included in the try clause generates an error, the code in the catch clause (corresponding to that error - you can have multiple catch for a single try) will be executed. 它比这简单得多 - 如果try子句中包含的任何子句生成错误,catch子句中的代码(对应于该错误 - 您可以在一次尝试中有多个catch)将被执行。 There is no way to know in advance if a particular clause will fail or not, only to try to recover after the error happens. 没有办法事先知道特定子句是否会失败,只是在错误发生后尝试恢复。

If you have ten clauses and the last one throws an error, the modifications performed by the first 9 will not be "reverted"! 如果你有10个子句而最后一个抛出错误,那么前9个执行的修改将不会被“恢复”!

The code which can give some unexpected result which the program can't handle is kept inside the try block,and to handle/catch the unexpected crashing of the program we use catch block.Where we declare type of Exception the code can throw 可以给出一些程序无法处理的意外结果的代码保存在try块中,并且处理/捕获我们使用catch块的程序的意外崩溃。我们声明代码可以抛出的Exception类型

Eg: 例如:

 int a;
 try {
  a=1/0;//program wil crash here
 }catch(Exception e){
  System.out.println("Division by zero ");//handling the crash here
 }

It starts executing normally, w/o any checking. 它开始正常执行,没有任何检查。 If any exception occurs, it will break out of the clause (like break in a loop), and immediately execute the catch , if no exception was found, it will skip the catch clause. 如果发生任何异常,它将突破该子句(如循环中的break ),并立即执行catch ,如果没有找到异常,它将跳过catch子句。

The finally clause, insures that it will be called no matter if an exception was thrown, or not. finally子句确保无论是否抛出异常都会调用它。 A practical example would be reading from a file or network, and close the streams, no matter if an exception was thrown or not. 一个实际的例子是从文件或网络读取,并关闭流,无论是否抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM