我如何在 Java Jar CMD 上打印自己的错误消息

发布于 2025-01-12 23:19:16 字数 782 浏览 1 评论 0 原文

如何将附加信息打印到命令行控制台?

现在的输出是:

C:\Users\admin\Desktop\java>java -jar pdf.jar
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
        at readDataIn.main(readDataIn.java:31)

代码:

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        try {
            String arg = args[0];
            fileNameSource = "import/" + arg + ".xml";
            fileNameTarget = "export/" + arg + ".pdf";
        } catch (Exception e) {
            // TODO: handle exception
            **System.out.println("Personal-Number is missing");**
            e.printStackTrace();
            
        }

我如何给出信息,即个人号码丢失?

how can I Print adittional information to Command line Console?

Output now is:

C:\Users\admin\Desktop\java>java -jar pdf.jar
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
        at readDataIn.main(readDataIn.java:31)

Code:

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        try {
            String arg = args[0];
            fileNameSource = "import/" + arg + ".xml";
            fileNameTarget = "export/" + arg + ".pdf";
        } catch (Exception e) {
            // TODO: handle exception
            **System.out.println("Personal-Number is missing");**
            e.printStackTrace();
            
        }

How can i give the information out, that the Personal Number ist Missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

指尖凝香 2025-01-19 23:19:16

首先,作为一般规则,如果可能的话,您应该在实际发生之前检查可能的异常,在您的情况下肯定是这样。
因此,不要捕获 ArrayIndexOutOfBounds ,而是插入一个 if 语句,该语句在访问之前检查 args 数组的长度。

if(args.length == 0){
   // no argument has been provided
   // handle error here
}

就如何处理错误而言,有很多可用的选项,并且根据您想要执行的操作,其中任何一个都可能是一个不错的选择。

IllegalArgumentException

这是 Java 中的一个常见习惯用法,每当函数接收到无效/非法参数时就会抛出 IllegalArgumentException

if (args.length == 0){
    throw new IllegalArgumentException("Personal number is missing");
}

这将打印您提供的消息和堆栈跟踪。但是,如果您的应用程序应该是命令行界面 (CLI),则不应使用这种错误处理。

打印消息&有关

if (args.length == 0){
    // notice: "err" instead of "out": print to stderr instead of stdout
    System.err.println("Personal number is missing");
    // exit program with non-zero exit code as exit code == 0 means everything is fine
    System.exit(1);
}

stdoutstderr 的更多信息,请参阅此 StackOverflow 问题
这就是许多 CLI 应用程序和例如 java 本身所做的事情。当您输入 java fdsdfsdfs 或一些类似的废话作为参数时,Java 会给您一条错误消息并以一些非零返回代码(在本例中为“1”)退出。
CLI 应用程序通常会打印错误消息并跟踪一些有关如何正确使用应用程序的使用信息,或提供帮助命令以便用户可以获得更多信息。例如,如果您仅输入 java 而不带任何参数,就会发生这种情况。
所以这真的取决于你想做什么。

如果您正在考虑使用更多(复杂)命令和多个选项等来实现功能齐全的 CLI 应用程序,您应该考虑使用 CLI 库,例如 JCommanderApache Commons CLI 解析命令行参数很快就会变得丑陋。所有这些常见的事情都已经在那里处理了。

日志记录

如果您的应用程序是以非交互式方式执行的某个脚本,则将错误记录到文件中并以非零退出代码退出也可能是一种选择。

PS

在我看来,您的代码根本不应该编译,因为您没有声明变量 fileNameSourcefileNameTarget 的类型。
此处使用 Stringvar(假设您运行的是 > Java 11)。

String fileNameSource = "import/" + arg + ".xml";
var fileNameTarget = "export/" + arg + ".pdf";

您可能还需要考虑您的程序名称是 args 数组的一部分,因此数组中可能有多个值,因此可能需要调整 if上面的陈述。

First of all, as a general rule you should check for possible exceptions before they actually occur if that is possible, which in your case it definitely is.
So instead of catching the ArrayIndexOutOfBounds insert an if statement that checks the length of the args array before accessing it.

if(args.length == 0){
   // no argument has been provided
   // handle error here
}

In terms of how to handle the error, there are many options available and depending of what you want to do either could be a good fit.

IllegalArgumentException

It is a common idiom in Java that whenever a function receives an invalid/ illegal argument to throw an IllegalArgumentException.

if (args.length == 0){
    throw new IllegalArgumentException("Personal number is missing");
}

This will print the message that you have provided and the stack trace. However if your application should be a Command Line Interface (CLI) you should not use this kind of error handling.

Print message & exit program

if (args.length == 0){
    // notice: "err" instead of "out": print to stderr instead of stdout
    System.err.println("Personal number is missing");
    // exit program with non-zero exit code as exit code == 0 means everything is fine
    System.exit(1);
}

For more information on stdout and stderr see this StackOverflow question.
This is what many CLI applications and e.g. java itself does. When you type java fdsdfsdfs or some similar nonsense as an argument Java will give you an error message and exit with some non-zero return code ("1" in this case).
It is also common that CLI applications print an error message and following some usage information on how to correctly use the application or provide a help command so a user can get more information. This happens for example if you just enter java without any parameters.
So it is really up to you what you want to do.

If you are thinking of implementing a full featured CLI application with more (complex) commands with multiple options etc. you should consider using a CLI library like JCommander or Apache Commons CLI as parsing command line arguments can quickly get ugly. All these common things are already handled there.

Logging

In case your application is some script that will be executed in a non-interactive way logging the error to a file and exiting with a non-zero exit code might also be an option.

PS

Your code looks to me like it should not compile at all as you are not declaring a type for your variables fileNameSource and fileNameTarget.
Use String or var here (assuming you're running > Java 11).

String fileNameSource = "import/" + arg + ".xml";
var fileNameTarget = "export/" + arg + ".pdf";

You might also need to consider that your program name is part of the args array, so you might have more than 0 values in the array and therefore might need to adjust the if statements above.

喜你已久 2025-01-19 23:19:16

您可能对 picocli 感兴趣,它是一个用于 Java 和其他 JVM 语言的现代 CLI 库。

Picocli 自动执行一些基本验证,并生成非常紧凑的代码,从而生成用户友好的应用程序。例如:

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

@Command(name = "myapp", mixinStandardHelpOptions = true, version = "1.0",
        description = "This command does something useful.")
class MyApp implements Runnable {

    @Parameters(description = "File name (without extension) of the file to import and export.")
    private String personalNumber;

    @Override
    public void run() {
        String fileNameSource = "import/" + personalNumber + ".xml";
        String fileNameTarget = "export/" + personalNumber + ".pdf";

        // remaining business logic
    }

    public static void main(String[] args) {
        System.exit(new CommandLine(new MyApp()).execute(args));
    }
}

如果我在没有任何参数的情况下运行此类,则以下消息将打印到标准错误流,并且该过程以退出代码 2 结束。(退出代码为 可自定义。)

Missing required parameter: '<personalNumber>'
Usage: myapp [-hV] <personalNumber>
This command does something useful.
      <personalNumber>   File name (without extension) of the file to import
                           and export.
  -h, --help             Show this help message and exit.
  -V, --version          Print version information and exit.

使用帮助消息是根据命令的描述及其选项和位置参数的描述自动创建的,但可以进一步自定义。

请注意 mixinStandardHelpOptions = true 注释如何向命令添加 --help--version 选项。这些选项由库处理,不需要应用程序中的任何进一步逻辑。

Picocli 附带一个注释处理器,可以非常轻松地注释处理器。 info/#_graalvm_native_image" rel="nofollow noreferrer">使用 GraalVM 将您的应用程序转换为原生映像。与 Java VM 相比,本机映像具有更快的启动时间和更低的运行时内存开销。

You may be interested in picocli, which is a modern CLI library for Java and other JVM languages.

Picocli does some basic validation automatically, and results in very compact code that produces user-friendly applications. For example:

import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

@Command(name = "myapp", mixinStandardHelpOptions = true, version = "1.0",
        description = "This command does something useful.")
class MyApp implements Runnable {

    @Parameters(description = "File name (without extension) of the file to import and export.")
    private String personalNumber;

    @Override
    public void run() {
        String fileNameSource = "import/" + personalNumber + ".xml";
        String fileNameTarget = "export/" + personalNumber + ".pdf";

        // remaining business logic
    }

    public static void main(String[] args) {
        System.exit(new CommandLine(new MyApp()).execute(args));
    }
}

If I run this class without any parameters, the following message is printed to the standard error stream, and the process finished with exit code 2. (Exit codes are customizable.)

Missing required parameter: '<personalNumber>'
Usage: myapp [-hV] <personalNumber>
This command does something useful.
      <personalNumber>   File name (without extension) of the file to import
                           and export.
  -h, --help             Show this help message and exit.
  -V, --version          Print version information and exit.

The usage help message is created automatically from the descriptions of the command, and the descriptions of its options and positional parameters, but can be further customized.

Note how the mixinStandardHelpOptions = true annotation adds --help and --version options to the command. These options are handled by the library without requiring any further logic in the application.

Picocli comes with an annotation processor that makes it very easy to turn your application into a native image with GraalVM. Native images have faster startup time and lower runtime memory overhead compared to a Java VM.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文