Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display stack trace elements exclusive only the Java classes that I wrote

Tags:

java

enter image description here

As you see, these are all stack trace elements. I only want the yellow part that have blue fonts (clickable to identify the java class and its line number where the exception was thrown) to be printed as the rest of the stack traces are excess and redundant.

I managed to display those stack traces using:

public static void displayStackStraceArray(StackTraceElement[] stackTraceElements) { 
    for (StackTraceElement elem : stackTraceElements) {
        System.err.println("\t"+elem.toString());
    }
}
like image 656
Daryll David Dagondon Avatar asked Apr 26 '26 13:04

Daryll David Dagondon


2 Answers

You may check each stack trace entry for mention of your class file at the end of the line:

public static void displayStackStraceArray(StackTraceElement[] stackTraceElements) { 
    for (StackTraceElement elem : stackTraceElements) {
        String line = elem.toString();
        // assuming the file is called Search_Task.java:
        if (line.matches(".*\\(Search_Task\\.java:\\d+\\)$")) {
            System.err.println("\t"+elem.toString());
        }
    }
}
like image 112
Tim Biegeleisen Avatar answered Apr 29 '26 02:04

Tim Biegeleisen


As JB Nizet notes in a comment, you should use your own specific package instead of starting it with android.

public static final String PACKAGE_ROOT = "org.example.application";

public static void displayStackStraceArray(StackTraceElement[] stackTraceElements) { 
    for (StackTraceElement elem : stackTraceElements) {
        if (elem.getClassName().startsWith(PACKAGE_ROOT)) {
            System.err.println("\t"+elem.toString());
        }
    }
}
like image 21
FThompson Avatar answered Apr 29 '26 04:04

FThompson