为什么下面的java代码不能编译?
坦率地说,我只是不明白我的导师要我在这里做什么。我尝试过使用try-catch块,以及在方法签名中抛出异常。我读过有关检查和未检查异常的内容。我肯定这会被否决或关闭,但有人能扔我一根骨头吗?我的导师的指示如下: 更正它,使其编译为什么下面的java代码不能编译?,java,exception-handling,Java,Exception Handling,坦率地说,我只是不明白我的导师要我在这里做什么。我尝试过使用try-catch块,以及在方法签名中抛出异常。我读过有关检查和未检查异常的内容。我肯定这会被否决或关闭,但有人能扔我一根骨头吗?我的导师的指示如下: 更正它,使其编译 class Exception3{ public static void main(String[] args){ if (Integer.parseInt(args[0]) == 0) thr
class Exception3{
public static void main(String[] args){
if (Integer.parseInt(args[0]) == 0)
throw new Exception("Invalid Command Line Argument");
}
}
很明显,它正在抛出RuntimeException。更具体地说是ArrayIndexOutOfBoundsException。我知道异常的原因是因为数组是空的,所以引用的索引不存在。我的意思是,从技术上讲,我可以删除ifInteger.parseIntargs[0]==0并抛出新的ExceptionInvalid命令行参数;并将其替换为System.out.printlnIt立即编译
有什么想法吗
public static void main(String[] args) throws Exception{
if (Integer.parseInt(args[0]) == 0)
throw new Exception("Invalid Command Line Argument");
}
您的方法引发异常,所以方法声明应该指定它可能引发异常
依照
已检查的例外情况受Catch或Specify要求的约束。所有异常都是检查异常,错误、RuntimeException及其子类指示的异常除外
您的方法引发异常,所以方法声明应该指定它可能引发异常
依照
已检查的例外情况受Catch或Specify要求的约束。所有异常都是检查异常,错误、RuntimeException及其子类指示的异常除外
您必须使用try-catch语句捕获它:
class Exception3 {
public static void main(String[] args) {
try {
if (Integer.parseInt(args[0]) == 0)
throw new Exception("Invalid Command Line Argument");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
或者在方法标题处声明它:
class Exception3 {
public static void main(String[] args) throws Exception {
if (Integer.parseInt(args[0]) == 0)
throw new Exception("Invalid Command Line Argument");
}
}
您必须使用try-catch语句捕获它:
class Exception3 {
public static void main(String[] args) {
try {
if (Integer.parseInt(args[0]) == 0)
throw new Exception("Invalid Command Line Argument");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
或者在方法标题处声明它:
class Exception3 {
public static void main(String[] args) throws Exception {
if (Integer.parseInt(args[0]) == 0)
throw new Exception("Invalid Command Line Argument");
}
}
就这样?这就是我要做的一切?勒芒!这是我两小时前做的第一件事!我之所以如此沮丧,并决定来到这里,是因为我在运行这该死的东西时得到了这个。主线程java.lang.ArrayIndexOutOfBoundsException中出现异常:0编译时间与运行时不同。ArrayIndexOutofbounds是运行时异常。如果我正确理解您的教授,他/她只是在寻找成功的编译。如果您通过传递值不是0的参数来运行,您的程序将不会出现任何问题。好的,我非常感谢您在这方面花费的时间,并感谢您的帮助。就这样?这就是我要做的一切?勒芒!这是我两小时前做的第一件事!我之所以如此沮丧,并决定来到这里,是因为我在运行这该死的东西时得到了这个。主线程java.lang.ArrayIndexOutOfBoundsException中出现异常:0编译时间与运行时不同。ArrayIndexOutofbounds是运行时异常。如果我正确理解您的教授,他/她只是在寻找成功的编译。如果您通过传递值不是0的参数来运行,您的程序将不会出现任何问题。非常感谢您在这方面花时间,并感谢您的帮助。