Monday, August 18, 2014

NETBEANS Java Basics 112 – Java Stack Trace

---
Java Basics 112– Java Stack Trace

STEPS

1) Open Startup Project

Continue from the previous tutorial or create a new project as follows.
Project Name: errorhandling
Main Class Name: errorhandling .errorChecking

2) Begin with Startup Codes.

2-1) Replace the generated codes with the following codes (which has discarded all comments and unnecessary codes).
package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        System.out.println("Starting Main method");
        m1();
        System.out.println("End Main method");
    }
    static void m1() {
        System.out.println("Method One - m1");
        m2();
    }
    static void m2() {
        System.out.println("Method One - m2");
    }
}
2-2) Run.

3) Edit the Method m2 so that it contains errors

3-1) Paste the codes to method m2.
package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        System.out.println("Starting Main method");
        m1();
        System.out.println("End Main method");
    }
    static void m1() {
        System.out.println("Method One - m1");
        m2();
    }
    static void m2() {
        int x = 10;
        int y = 0;
        double z = x / y;
        System.out.println(z);
        System.out.println("Method Two - m2");
    }
}
3-2) Run.

4) Edit method m1 so that it contains TRY…CATCH block.

4-1) Add the codes.
package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        System.out.println("Starting Main method");
        m1();
        System.out.println("End Main method");
    }
    static void m1() {
        try {
            System.out.println("Method One - m1");
            m2();
        } catch (ArithmeticException err) {
            System.out.println(err.getMessage());
        }
    }
    static void m2() {
        int x = 10;
        int y = 0;
        double z = x / y;
        System.out.println(z);
        System.out.println("Method Two - m2");
    }
}
4-2) Run.
Info:
If you see a stack trace in the Output window, just remember that first line is where the problem occurred; the rest of the lines, if any, are where the Exception was handed up the stack, usually finishing at the main method.

REFERENCE


---

No comments:

Post a Comment