Monday, August 18, 2014

NETBEANS Java Basics 111 – Error Handling

---
Java Basics 111– Error Handling

STEPS

1) Create New Project

Project Name: errorhandling
Main Class Name: errorhandling.errorChecking
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) {
        // TODO code application logic here
    }
   
}

2) Add TRY… CATCH block.


package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        try {
        } catch (Exception err) {
        }
    }
}

3) Add TRY Content (valid logic).

3-1) Add statements that contain valid logic.

package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        try {
            int x = 10;
            int y = 1;
            int z = x / y;
            System.out.println(z);
        } catch (Exception err) {
        }
    }
}
3-2) Run and observe the output.

4) Add TRY Content (invalid logic).

4-1) Add statements that contain invalid logic.

package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        try {
            int x = 10;
            int y = 0;
            int z = x / y;
            System.out.println(z);
        } catch (Exception err) {
        }
    }
}
4-2) Run and observe the output.

5) Add CATCH content.

5-1) Add the error response statement.

package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        try {
            int x = 10;
            int y = 0;
            int z = x / y;
            System.out.println(z);
        } catch (Exception err) {
            System.out.println(err.getMessage());
        }
    }
}
5-2) Run and observe the output.

6) Additional Exercise.

What is the output of the following codes?

package errorhandling;
public class errorChecking {
    public static void main(String[] args) {
        try {
            double x = 10.0;
            double y = 0.0;
            double z = x / y;
            System.out.println(z);
        } catch (Exception err) {
            System.out.println(err.getMessage());
        }
    }
}

REFERENCE

---

No comments:

Post a Comment