Contoh Program Exception dalam Bahasa Java

Konsep exception digunakan untuk menghindari terjadinya program mati/ berhenti mendadak saat sedang dijalankan. Hal ini biasanya disebabkan isian dari user yang tidak sesuai, atau ada proses di dalam program yang menyebabkan error di tengah jalan. Struktur coding-nya adalah berupa blok try {} catch(){} finally{}. Berikut ini adalah contoh sederhananya.


import java.io.*;
class ExceptionGenerator {
public void divideByZero () {
    // Generate an ArithmeticException - runtime
    int y = 6, x = 0;
    int z = y / x;
    System.out.println ("z = " + z);
}
public void arrayOutOfBounds () {
    // Generate an ArrayIndexOutOfBoundsException - runtime
    int [] data = new int [10];
    data[10] = 16;
    System.out.println ("data[10] = " + data[10]);
}

public void badCast () throws IOException {
    // Generate a NumberFormatException - runtime
    BufferedReader keyboard = new BufferedReader (
    new InputStreamReader (System.in));
    System.out.print ("Enter an integer: " );
    String line = keyboard.readLine();
    int value = (new Integer(line)).intValue();
    System.out.println("value = " + value);
}
public void numericInput () {
    try {
        // Have user input a string representing a number
        BufferedReader keyboard = new BufferedReader (
        new InputStreamReader(System.in));
        System.out.print ("Enter an integer: " );
        String line = keyboard.readLine();
        int value = (new Integer(line)).intValue();
        System.out.println("value = " + value);
    }
    catch (IOException ex) {
        System.out.println ("IO exception in reading user input." );
    }
    catch (NumberFormatException ex) {
        System.out.println ("Invalid integer entered." );
    }
}
public void numericInputWithException () {
    try {
        // Have user input a string representing a number
        BufferedReader keyboard = new BufferedReader (
        new InputStreamReader (System.in));
        System.out.print ("Enter an integer: " );
        String line = keyboard.readLine();
        int value = (new Integer(line)).intValue();
        System.out.println("value = " + value);
    }
    catch (IOException ex) {
        System.out.println ("IO exception in reading user input." );
    }
}
}

public class exceptions {
    // Fields
    ExceptionGenerator except = new ExceptionGenerator();
    int choice;
    BufferedReader keyboard = new BufferedReader (
    new InputStreamReader(System.in));
    // Commands
    public void generateExceptions () {
        System.out.println ("2 --> Divide by zero" );
        System.out.println ("3 --> Array index range error" );
        System.out.println ("4 --> Bad cast" );
        System.out.println ("5 --> Bad numeric input" );
        System.out.println ("6 --> Trap bad numeric input" );
        System.out.print("Enter choice: " );
        try {
            choice = (new Integer(keyboard.readLine())).intValue();
        }
        catch (IOException ex) { // do nothing
        }
        switch (choice) {
            case 2:
                except.divideByZero();
                break;
            case 3:
                except.arrayOutOfBounds();
                break;
            case 4:
                try {
                except.badCast();
                }
                catch (IOException ex) {
                } // Unhandled exception
                finally{
                    System.out.println("It's catched...");
                }
                break;
            case 5:
                except.numericInput ();
                break;
            case 6:
                try {
                    except.numericInputWithException();
                }
                catch (NumberFormatException ex) {
                    try {
                    // Second and final chance
                        except.numericInputWithException ();
                    }
                    catch (Exception e) {}
                }
                finally {
                    System.out.println ("In finally block." );
                }
                break;
        }
    }
    public static void main (String[] args) {
        exceptions app = new exceptions ();
        app.generateExceptions();
    }
}

No comments:

Post a Comment