【问题标题】:Java Analog for Raising Error in Python用于在 Python 中引发错误的 Java 模拟
【发布时间】:2015-03-03 15:22:57
【问题描述】:

我想引发一个错误并终止一个 Java 程序,但我很困惑如何去做,因为它似乎与我在 Python 中的做法有着根本的不同。

在 Python 中我会写:

import sys

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

这会产生:

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

这就是我想要的,因为我不想捕捉错误。

在 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");
        }
    }
}

但是 NetBeans 告诉我它“找不到符号”IOException

我找到了抛出异常的这些答案:

Java unreported exception

How to throw again IOException in java?

但他们都建议定义全新的类。这是必要的吗?即使 IOException 属于 Throwable 类?

我对 Python 和 Java 之间区别的根本误解阻碍了我。我如何基本上实现我的 python 示例所取得的成就?在 Java 中引发该错误的最接近的复制是什么?

谢谢

【问题讨论】:

  • 你不需要定义一个全新的类。扔一个标准的throw new IllegalArgumentException("Please check...");
  • 好的,是的!我希望它是这样简单的。谢谢。

标签: java python error-handling throw


【解决方案1】:

IOException 属于java.io 包,你应该先导入它。这也是一个“已检查”异常,这意味着您应该修改您的main 方法,添加throws IOException,或者在方法体中捕获它。

import java.io.IOException;

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

我同意@pbabcdefp 的观点,您应该使用IllegalArgumentException,它是RuntimeException,不需要在代码中明确处理。

【讨论】:

    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多