Avatar ·

How to convert StackTrace to a string in Java?

Hello everyone! I'm a beginner Java developer and I've encountered a problem when working with exceptions. I need to log errors to a text file, but the standard printStackTrace() method only outputs the stack trace to the console (System.err). I want to get the full stack trace as a string so I can save it to a file, send it by email, or simply output it to a log file. Here's an example of my code: ```java try { // some code that may throw an exception int result = 10 / 0; } catch (Exception e) { // here I need to get the stack trace as a string e.printStackTrace(); // this only outputs to the console // but I want something like: // String stackTraceString = convertStackTraceToString(e); // System.out.println(stackTraceString); // or write to a file } ```