英文:
Constructor in the Try/Catch block
问题
以下是代码的翻译:
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();
}
}
英文:
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. 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();
}
}
答案1
得分: 2
**因为赋值语句是语句,而语句只允许在代码块(方法、构造函数、静态初始化器等)内部。**以下是整理过的代码示例:
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 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();
}
}
}
答案2
得分: 1
因为构造函数是一个声明,而不是一个语句。
你的构造函数可以被其他代码调用,但仅仅声明它不会执行它;这就是 new Test()
所做的。仅仅声明构造函数不会执行任何操作,因此也没有任何可能抛出异常的内容。因此,也就没有需要捕获的内容。
从更一般的语法角度来说,不会求值的语句只能存在于构造函数、方法和初始化块中。
然而,你可以这样做:
public static void main(String[] args) {
try {
Test test = new Test();
} catch (Exception e) {
System.out.println(e);
}
}
new Test()
实际上执行了构造函数,这就是为什么它可能会抛出异常,因此你可以合法地尝试捕获它可能抛出的任何异常。从语法上讲,上述所有代码都在一个方法中(即 main
方法),这是允许的。
英文:
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. 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. Syntactically, all of the above code is inside a method (the main
method), which is allowed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论