|
Just fooling around with looking at Java exceptions today, I created the following sample code to see what the output from various exception-printing approaches looked like. I usually just follow the e.printStackTrace() approach, but I wanted to learn a little more about the options, as I was getting ready to print my exception information using a tool like Log4j.
So, here's the example Java source code for the exception testing class I created:
package com.devdaily.tests;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Properties;
public class ExceptionTest
{
public ExceptionTest()
{
Properties props = new Properties();
try
{
props.load(new FileInputStream(new File("foo")));
}
catch (Exception e)
{
System.err.println("1");
System.err.println(e);
System.err.println("\n2");
System.err.println(e.getMessage());
System.err.println("\n3");
System.err.println(e.getLocalizedMessage());
System.err.println("\n4");
System.err.println(e.getCause());
System.err.println("\n5");
System.err.println(Arrays.toString(e.getStackTrace()));
System.err.println("\n6");
e.printStackTrace();
}
}
public static void main(String[] args)
{
new ExceptionTest();
}
}
Given that simple test class, and knowing that there isn't a file named "foo", here's the output from the class:
1
java.io.FileNotFoundException: foo (The system cannot find the file specified)
2
foo (The system cannot find the file specified)
3
foo (The system cannot find the file specified)
4
null
5
[java.io.FileInputStream.open(Native Method), java.io.FileInputStream.(FileInputStream.java:106), com.devdaily.tests.ExceptionTest.(ExceptionTest.java:15), com.devdaily.tests.ExceptionTest.main(ExceptionTest.java:36)]
6
java.io.FileNotFoundException: foo (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:106)
at com.devdaily.tests.ExceptionTest.(ExceptionTest.java:15)
at com.devdaily.tests.ExceptionTest.main(ExceptionTest.java:36)
For my money, option #6 certainly prints out the information I'm looking for. The next thing to do is to try to integrated this with Log4j. I don't have Log4j on the system I'm typing this one, so I'll have to take a look at that tomorrow.
|