簡體   English   中英

Java Analog引發Python錯誤

[英]Java Analog for Raising Error in Python

我想引發一個錯誤並終止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未報告的異常

如何在Java中再次拋出IOException?

但是他們都建議定義全新的類。 這有必要嗎? 即使IOException屬於Throwable類?

我對Python和Java之間差異的根本誤解在這里妨礙了我。 我基本上如何實現我的python示例所達到的目標? Java中引發錯誤的最接近的復制方式是什么?

謝謝

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 ,不需要在代碼中顯式處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM