Stack Trace & Logging Exceptions in Java
A stack trace is a detailed report that shows where an exception occurred and the sequence of method calls that led to it.
It helps developers debug and trace errors easily.
What is a Stack Trace?
A stack trace is a detailed report that shows the sequence of method calls when an exception occurs.
It helps developers identify:
- The type of exception
- The error message
- The exact file & line number
- The call hierarchy (method-by-method stack)
Stack traces are extremely useful for debugging runtime errors.
Example of Stack Trace
public class StackTraceExample {
public static void main(String[] args) {
try {
int a = 10 / 0; // ArithmeticException
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
java.lang.ArithmeticException: / by zero
at StackTraceExample.main(StackTraceExample.java:5)
This shows:
- Exception type: ArithmeticException
- Reason: / by zero
- Location: line 5
Ways to Print Stack Trace

1. printStackTrace()
Most common method.
catch (Exception e) {
e.printStackTrace();
}
2. getMessage()
Prints only error message.
System.out.println(e.getMessage());
3. toString()
Prints exception type + message.
System.out.println(e.toString());
4. Convert Stack Trace to String
Useful for logging.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String stackTrace = sw.toString();
Why Stack Trace Is Important?
- Shows exact cause of failure
- Includes line numbers
- Helps debug complex issues
- Very useful in production logs
Logging Exceptions in Java
Printing errors using System.out or printStackTrace() is not recommended in real-world applications.
Logging helps track exceptions in:
- Log files
- Cloud logs
- DB logs
- Consoles
Java supports many logging frameworks.
Logging Using java.util.logging
import java.util.logging.*;
public class LoggingExample {
private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());
public static void main(String[] args) {
try {
String s = null;
s.length();
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception occurred", e);
}
}
}
Logging with Log4j
import org.apache.log4j.Logger;
public class Log4jExample {
static Logger logger = Logger.getLogger(Log4jExample.class);
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (Exception e) {
logger.error("Error occurred: ", e);
}
}
}
Logging with SLF4J + Logback (Most Popular)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SLF4JExample {
private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);
public static void main(String[] args) {
try {
int[] arr = new int[3];
int x = arr[5];
} catch (Exception e) {
logger.error("Exception happened: {}", e.getMessage(), e);
}
}
}
Why Use Logging Instead of printStackTrace()?
| Feature | printStackTrace() | Logging Framework |
|---|---|---|
| Console Output | Only console | Console + File + Cloud |
| Log File Support | Not supported | Writes logs to files |
| Log Levels (ERROR, WARN, INFO, DEBUG) | No levels | Supports all log levels |
| Production Ready | Not suitable | Used in enterprise apps |
| Structured Logs (JSON, XML) | Not possible | Supported |
| Configurable Output Format | No | Fully configurable |
| Performance Optimization | No control | Async + buffered logging |
| Supports External Tools | No | Works with ELK, Splunk, etc. |
Log Levels in Java
- ERROR → Serious failure
- WARN → Possible problem
- INFO → General information
- DEBUG → Detailed debugging
- TRACE → Very deep debugging
Best Practices for Logging Exceptions
- Always log exceptions with context
- Avoid
System.out.println()in production - Don’t swallow exceptions silently
- Don’t duplicate logs across layers
- Use SLF4J for modern applications
Real-World Logging Example
try {
processData();
} catch (IOException e) {
logger.error("Failed to process file", e);
}
Logs include:
- Custom message
- Full stack trace
