StackTraceElement
Last updated
public class StackTraceElementExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Causes ArithmeticException
} catch (ArithmeticException e) {
StackTraceElement[] stackTrace = e.getStackTrace();
for (StackTraceElement element : stackTrace) {
System.out.println(element); // Output: ClassName.MethodName(FileName:LineNumber)
}
}
}
}public class StackTraceElementDetails {
public static void main(String[] args) {
try {
throw new RuntimeException("Test Exception");
} catch (RuntimeException e) {
StackTraceElement element = e.getStackTrace()[0];
System.out.println("Class: " + element.getClassName()); // Output: Class: StackTraceElementDetails
System.out.println("Method: " + element.getMethodName()); // Output: Method: main
System.out.println("File: " + element.getFileName()); // Output: File: StackTraceElementDetails.java
System.out.println("Line: " + element.getLineNumber()); // Output: Line: [line number]
System.out.println("Is Native: " + element.isNativeMethod()); // Output: Is Native: false
}
}
}public class StackTraceElementToString {
public static void main(String[] args) {
try {
throw new Exception("Sample Exception");
} catch (Exception e) {
System.out.println(e.getStackTrace()[0].toString()); // Output: ClassName.MethodName(FileName:LineNumber)
}
}
}public class CustomStackTrace {
public static void main(String[] args) {
try {
recursiveMethod(5);
} catch (StackOverflowError e) {
for (StackTraceElement element : e.getStackTrace()) {
if (element.getClassName().contains("CustomStackTrace")) {
System.out.println("Found Method: " + element.getMethodName()); // Output: Found Method: recursiveMethod
}
}
}
}
public static void recursiveMethod(int n) {
if (n == 0) return;
recursiveMethod(n - 1);
}
}