gpt4 book ai didi

java - 处理/处理错误流消息的最佳方式

转载 作者:搜寻专家 更新时间:2023-11-01 01:20:54 25 4
gpt4 key购买 nike

我需要处理编译/运行时生成的不同错误/异常消息。

我执行一个 Java 程序并读取由此生成的流:

final Process p2 = builder.start();
BufferedReader in = new BufferedReader(new
InputStreamReader(p2.getInputStream()));

对于每次成功,都会生成并显示输出。没问题。但我需要为每条错误消息显示自定义消息。

如:

Error: Main method not found in class dummy.helloParse10.hello, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

可以自定义为:错误:找不到主要方法

我目前的做法非常丑陋和有限。我正在查看错误流中是否存在“异常”字符串,然后取出子字符串。类似于:

if(tError.contains("Exception"))            
tError=tError.substring(tError.indexOf("main\"")+5,tError.indexOf("at"))
+ "( At Line: "+tError.substring(tError.indexOf(".java")+6);

但它并没有广泛地定制我的方法。

我能做的最好的事情是什么?

编辑:

我觉得我的问题不清楚。基本上我通过ProcessBuilder.

    //Compile the program 
Process p = Runtime.getRuntime().exec("javac filename ");

// Now get the error stream if available :
BufferedReader in = new BufferedReader(new
InputStreamReader(p.getOutputStream()));

String line = null;
while ((line = in.readLine()) != null) {

//process error in compilation.
}
...
...
// ProcessBuilder to execute the program.java
//Read the output or runtime Exception

进程的输出不能是 te java 程序的结果或从进程流中获取的字符串形式的异常/错误。需要处理这些错误。

更新:

我现在可以通过 Java Compiler API 解决编译时错误正如@Miserable Variable 所建议的那样。我怎样才能类似地处理运行时异常?

编辑:实际上,不可能修改要在新进程中运行的程序。它们是用户特定的。

最佳答案

为了识别编译中的错误,而不是使用 ProcessBuilder 运行 javac,更好的选择可能是使用 Java Compiler API .

我自己从未使用过它,但它看起来非常简单。

关于java - 处理/处理错误流消息的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33614909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com