try { // some code that throws an exception } catch (Exception e) { StackTraceElement[] stackTrace = e.getStackTrace(); StackTraceElement[] newStackTrace = new StackTraceElement[stackTrace.length + 1]; newStackTrace[0] = new StackTraceElement("Main", "main", "Main.java", 10); // add a custom element to stack trace System.arraycopy(stackTrace, 0, newStackTrace, 1, stackTrace.length); e.setStackTrace(newStackTrace); // set the new stack trace for the exception throw e; // re-throw the exception }
public class CustomException extends Exception { public CustomException() { super(); setStackTrace(new StackTraceElement[] { new StackTraceElement("CustomException", "CustomException", "CustomException.java", 10), // add more elements to stack trace if needed }); } public CustomException(String message) { super(message); setStackTrace(new StackTraceElement[] { new StackTraceElement("CustomException", "CustomException", "CustomException.java", 10), // add more elements to stack trace if needed }); } // add more constructors and methods as needed }In this example, we define a custom exception class that sets its own stack trace in the constructor. This can be useful when we want to provide a more meaningful stack trace for our custom exceptions. Package/Library: Depends on where the CustomException class is defined.