Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于try-catch语句与finally的java问题_Java_Algorithm - Fatal编程技术网

关于try-catch语句与finally的java问题

关于try-catch语句与finally的java问题,java,algorithm,Java,Algorithm,下面是一个由java编写的代码 public class work2{ public static void main(String args[]) { try { int x = 0; for (x=1; x<4; x++); System.out.println(x); } catch(Exception e) {} finally { System.out.println("Error

下面是一个由java编写的代码

public class work2{
public static void main(String args[]) {
    try {
        int x = 0;
        for (x=1; x<4; x++); 
        System.out.println(x);
    } catch(Exception e) {}
    finally {
        System.out.println("Error");
    }
}
公共类工作2{
公共静态void main(字符串参数[]){
试一试{
int x=0;
对于(x=1;x
一个finally块包含所有必须执行的关键语句
无论是否发生异常都将执行。中的语句
无论是否发生异常,此块都将始终执行
在try块中或不在try块中,例如关闭连接、流等

无论发生什么情况,它都会打印“错误”。
因此,请尝试block printed 4,然后最后block print“Error”

您在
Try
块中写入导致异常的语句。这些异常使用
catch
块进行处理。
即使未触发异常,也会执行
最后的

在您的问题中,
x=0;
最初。由于循环的
后面有一个分号
,循环将执行3次,当
x=4
时,条件失败,它打印
x
的值,即4。最后执行
块。

public class Main{
    public class Main{
public static void main(String args[]) {
    try {
        int x = 0;
        for (x=1; x<4; x++)
        System.out.println(x);
    } catch(Exception e) {}
    finally {
        System.out.println("Error");
    }
}
}
公共静态void main(字符串参数[]){ 试一试{ int x=0;
对于(x=1;x您使用的
for
-循环只增加x的值,但不打印出来。因此,您将x增加到4,然后再打印出来,最终的部分仍将打印出来。 如果要输出x的每个值,必须在for
-循环的
之后添加
{}

它看起来像:

public class Main{
    public static void main(String args[]) {
        try {
            int x = 0;
            for (x=1; x<4; x++) {
                System.out.println(x);
            }
        } catch(Exception e) {}
        finally {
            System.out.println("Error");
        }
    }
}
公共类主{
公共静态void main(字符串参数[]){
试一试{
int x=0;

对于(x=1;x请始终记住在try-catch块中-“最终始终运行”,无论是否存在异常。现在进入代码。在try块中,您有以下行:

 try {
    int x = 0;
    for (x=1; x<4; x++); 
    System.out.println(x);
}

否我预期的输出是在新行上的
4
后跟
Error
,但无论如何,请删除(x=1;x)的尾部分号

public class Main{
    public static void main(String args[]) {
        try {
            int x = 0;
            for (x=1; x<4; x++) {
                System.out.println(x);
            }
        } catch(Exception e) {}
        finally {
            System.out.println("Error");
        }
    }
}
 try {
    int x = 0;
    for (x=1; x<4; x++); 
    System.out.println(x);
}
4
Error