Print the stackTrace and debug exceptions in java
stackTrace (call trace in French) is the representation of the stack during execution in java of the program. Exceptions are common in our programs when programmers compile their programs. The call trace allowed us to trace the source of the error.public static void main(String[] args) {
press(null);//line 9
}
static void press(int[] a) {
System.out.println("button "+a[0]);//line 12
}
Exception in thread "main" java.lang.NullPointerException
at myClass.press(StringCompare.java:12)
at myClass.main(StringCompare.java:9)
This example is simple, you can tell where the error happened by clicking on the last method called. The error is in line 12 and indicates access to a null object (NullPointerException). The only object present is a[0] so it is null and we notice that the press method is called in the main with a null parameter.
Example of try/catch
The method java.lang.Throwable.printStackTrace() prints the entire sequence from the beginning to the appearance of the exception as lines in descending order of the stack. The last row represents the root which is the first stacked method and the last represents the top of the stack whose error is in it. The lines are red because the display is done with it. System.err.
Exception in thread "main" java.lang.IllegalArgumentException: input == null!This exception is thrown by running the program:
at javax.imageio.ImageIO.read(Unknown Source)
at Fenetre.(Fenetre.java:127)
at Test.main(Test.java:9)
The Fenetre.java class opens and we can look for the cause in line 127 which indicates that the input stream is null. This means that the image was not found but why did it raise the exception?
Exception in thread "main" java.lang.IllegalArgumentException: input == null!We look for the type of exception in the catch and we notice that it is IOExeption because the getResource method must imperatively access the resource that is in file/icone.png otherwise in our case the image is not not accessible then an exception is thrown and the program stops.
References
What is a stack trace, and how can I use it to debug my application errors?
Class Throwable
How to print a stack trace to debug Java exceptions