Java 在方法中赋值throws子句
如何使用主方法签名中的Java 在方法中赋值throws子句,java,exception,main,Java,Exception,Main,如何使用主方法签名中的throws子句来处理异常,如下面的示例所示 import java.io.File; import java.io.IOException; public class Exception { public static void main(String ... args) throws IOException { ioExceptionTest(); } public static void ioExceptionTest()
throws
子句来处理异常,如下面的示例所示
import java.io.File;
import java.io.IOException;
public class Exception {
public static void main(String ... args) throws IOException {
ioExceptionTest();
}
public static void ioExceptionTest() throws IOException {
File file = new File("C:\\Users\\User\\Desktop\\Test.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
}
对我来说,这没有意义。如果一个方法使用
子句将子句抛出给它方法签名,那么在该方法中引发的任何异常都将引发给调用该方法的调用方。调用方可以选择使用try-catch块处理异常,或者使用throws子句将异常引发给调用它的人
main方法上的throws子句意味着异常将被引发到,它将处理异常并打印堆栈跟踪
class Example {
// handle exception with a try catch block
public static void main(String ... args) {
try {
myMethod();
} catch (Exception e) {
// handle the exception
}
}
// raise exception to the Java Virtual Machine
public static void main(String ... args) throws Exception {
myMethod();
}
static void myMethod() throws Exception {
// do something which may throw an Exception, such as
throw new Exception("Meaningful description");
}
}
如果一个方法使用抛出子句作为方法签名,那么在该方法中引发的任何异常都将引发给调用该方法的调用方。调用方可以选择使用try-catch块处理异常,或者使用throws子句将异常引发给调用它的人
main方法上的throws子句意味着异常将被引发到,它将处理异常并打印堆栈跟踪
class Example {
// handle exception with a try catch block
public static void main(String ... args) {
try {
myMethod();
} catch (Exception e) {
// handle the exception
}
}
// raise exception to the Java Virtual Machine
public static void main(String ... args) throws Exception {
myMethod();
}
static void myMethod() throws Exception {
// do something which may throw an Exception, such as
throw new Exception("Meaningful description");
}
}
请在问题中加入代码本身,而不是图像。根据你的回答,你的帖子可能会被给出。看一看,请在问题中加入代码本身,而不是图片。根据你的回答,你的帖子可能会被给出。看一看。