简体   繁体   English

Try/Catch 块中的构造函数

[英]Constructor in the Try/Catch block

The question is about the result of the below code.问题是关于以下代码的结果。 The answer is compilation error.答案是编译错误。 However I really do not understand why we can't have constructor in try/catch block.但是我真的不明白为什么我们不能在 try/catch 块中有构造函数。 I will put the the code below:我将把代码放在下面:

public class Test {
    try {
        public Test() {
            System.out.println("GeeksforGeeks");
            throw new Exception();
        }
    }
    catch(Exception e) {
        System.out.println("GFG");
    }
    
    public static void main(String [] args) {
        Test test= new Test();
    }
}

Because the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.) here's the clean code因为赋值是语句并且语句只允许在代码块(方法、构造函数、静态初始化器等)内使用,这里是干净的代码

public class Test {

    public Test()throws Exception {
        System.out.println("GeeksforGeeks");
        throw new Exception();
    }



public static void main(String [] args) {
    try {
        Test test= new Test();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

} }

Because a constructor is a declaration, not a statement.因为构造函数是声明,而不是语句。

Your constructor can be called by other code, but merely declaring it does not execute it;你的构造函数可以被其他代码调用,但仅仅声明它不会执行它; that's what new Test() does.这就是new Test()所做的。 Nothing is executed merely by declaring the constructor, so there is nothing that can throw an exception.仅通过声明构造函数不会执行任何操作,因此没有任何内容可以引发异常。 Thus, there is nothing to catch.因此,没有什么可捕捉的。

In more general syntax terms, statements which don't evaluate to a value can only exist in constructors, methods, and initialization blocks.在更一般的语法术语中,不求值的语句只能存在于构造函数、方法和初始化块中。

You can, however, do this:但是,您可以这样做:

public static void main(String[] args) {
    try {
        Test test = new Test();
    } catch (Exception e) {
        System.out.println(e);
    }
}

new Test() actually executes the constructor, which is why it may throw an exception and thus you can legally attempt to catch any exception it may throw. new Test()实际上执行构造函数,这就是它可能抛出异常的原因,因此您可以合法地尝试捕获它可能抛出的任何异常。 Syntactically, all of the above code is inside a method (the main method), which is allowed.从语法上讲,上述所有代码都在一个方法( main方法)中,这是允许的。

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

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