简体   繁体   English

Java程序失败时是否可以修改打印的堆栈跟踪?

[英]Can I modify the printed stack trace when a Java program fails?

I'm using IntelliJ idea, and everytime my program crashes when I'm doing test runs during the programming process I'm tired of seeing so many lines from the stacktrace, I just want to see a couple lines that tell me where my program failed or perhaps a dialog box. 我使用的是IntelliJ想法,每次在编程过程中进行测试运行时我的程序崩溃,我都厌倦了从堆栈跟踪中看到这么多行,我只想看几行来告诉我程序在哪里失败或对话框。 Is there any way I can achieve this in idea or Java in general? 总的来说,有什么办法可以实现我的想法或Java? Thanks 谢谢

This code prints only the first 5 lines of the stack trace of any Error or Exception that appears in the doStuff() method. 此代码仅打印出现在doStuff()方法中的任何错误或异常的堆栈跟踪的前5行。

public static void main(String[] args){
    try{
        doStuff();
    }
    catch(Throwable t){
        StackTraceElement[] elements = t.getStackTrace();
        for(int i = 0; i < 5; i++){
            System.err.println(elements[i]);
        }
    }
}

You can maybe create your custom exception by extending the Exception you want for the specific behavior of your application. 您可以通过扩展所需的应用程序特定行为的异常来创建自定义异常。 Then you can overwrite the method "setStackTrace", you can convert the stacktrace you get from an existing exception into a parameter that will be send to your new Exception class, you can thene xtract what you want from the existing stacktrace and modify it with the content you want. 然后,您可以覆盖方法“ setStackTrace”,可以将从现有异常中获取的堆栈跟踪转换为将发送到新Exception类的参数,可以从现有堆栈跟踪中提取所需内容,并使用您想要的内容。

class CustomException extends Exception {
        @Override
        public void setStackTrace(StackTraceElement[] stackTrace) {
            // Get elements I want from my stack trace
                    // Then I add what I want from the existing stacktrace and add some custom content
        }
    }

Best regards. 最好的祝福。

I think you should take a look at IntelliJ's console folding customization , which will only fold 'noisy' parts of your stacktrace. 我认为您应该看一下IntelliJ的控制台折叠自定义功能 ,它只会折叠您堆栈跟踪中“嘈杂”的部分。 You will still be able to see the whole stacktrace if needed (for example when you are trying to see who called your methods). 如果需要,您仍然可以查看整个stacktrace(例如,当您尝试查看谁调用了您的方法时)。

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

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