简体   繁体   English

Java Analog引发Python错误

[英]Java Analog for Raising Error in Python

I would like to raise an error and terminate a Java program, but I am confused how to do it, as it seems to be fundamentally different from how I would do it in Python. 我想引发一个错误并终止Java程序,但是我却对该方法感到困惑,因为它似乎与我在Python中的处理方法根本不同。

In Python I would write: 在Python中,我会写:

import sys

if len(sys.argv) != 2:
    raise IOError("Please check that there are two command line arguments")

Which would generate : 会产生:

Traceback (most recent call last):
  File "<pyshell#26>", line 2, in <module>
     raise OSError("Please check that there are two command line arguments")
OSError: Please check that there are two command line arguments

This is what I would like as I am not trying to catch the error. 这就是我想要的,因为我不想捕获错误。

In Java, I try to do something similar: 在Java中,我尝试做类似的事情:

public class Example {

    public static void main (String[] args){
        int argLength = args.length;
        if (argLength != 2) {
            throw IOException("Please check that there are two command line arguments");
        }
    }
}

However NetBeans tells me that it "cannot find symbol" IOException 但是NetBeans告诉我它“找不到符号” IOException

I have found these answers for throwing exceptions: 我发现了抛出异常的以下答案:

Java unreported exception Java未报告的异常

How to throw again IOException in java? 如何在Java中再次抛出IOException?

But they both recomend defining whole new classes. 但是他们都建议定义全新的类。 Is this necessary? 这有必要吗? Even though IOException belongs to the Throwable class? 即使IOException属于Throwable类?

My fundamental misunderstanding of the difference between Python and Java are hindering me here. 我对Python和Java之间差异的根本误解在这里妨碍了我。 How do I basically achieve what I have achieved with my python example? 我基本上如何实现我的python示例所达到的目标? What is the closest replication of that error raising in Java? Java中引发错误的最接近的复制方式是什么?

Thank you 谢谢

IOException belongs to the java.io package, you should import it first. IOException属于java.io包,您应该首先将其导入。 It is also a "checked" exception, which means that you should either modify your main method, adding throws IOException , or catch it in the method body. 这也是一个“已检查”异常,这意味着您应该修改main方法,添加throws IOException或将其捕获在方法主体中。

import java.io.IOException;

public class Example {
    public static void main(String [] args) throws IOException {
        ...
        throw new IOException("Please check that...");
    }
}

I agree with @pbabcdefp that you should use IllegalArgumentException which is a RuntimeException and does not need to be handled explicitly in the code. 我同意@pbabcdefp,应该使用IllegalArgumentException ,它是RuntimeException ,不需要在代码中显式处理。

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

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