Jumat, 05 Januari 2018

, ,

PEMROGRAMAN LANJUT BAB 9 : EXCEPTION HANDLING

Laporan Praktikum Pemrograman Lanjut Bab 9 Fakultas Ilmu Komputer Universits Brawijaya 2016/2017

Soal :
1.     Buatlah sebuah class turunan dari Exception baik di Java maupun C++ (pilih salah satu bahasa sesuai apa yang digunakan di praktikum) yang digunakan sebagai tipe exception yang dapat dilemparkan ketika menghitung n faktorial dimana n < 0. Buat method untuk menghitung faktorial terlebih dahulu!
2.       Lakukan reproduksi exception dan handlingnya dalam beberapa kasus dibawah (pilih minimal 2)
a.       I/O Exception
b.       Stack Overflow Exception

c.       Array index out of bound exception

Source code :
Class Bab9Exception
package bab9exception;

import java.util.Scanner;

public class Bab9Exception {

    static double fact(int s) {
        if (s < 0) {
            throw new IllegalArgumentException("Error");
        }
        int tot = 1;
        do {
            tot *= s;
            s--;
        } while (s > 0);
        return tot;
    }

    public static void main(String[] args) {
        Scanner sausan = new Scanner(System.in);
        double z;
        System.out.print("Enter number ");
        int m = sausan.nextInt();
        try {
            z = fact(m);
            System.out.println(z);
        } catch (Exception h) {
            System.out.println(h.getMessage());
        }
    }
}

Class Except
package bab9exception;

import java.util.Scanner;

public class Except {

    public static void main(String[] args) {
        Scanner sausan = new Scanner(System.in);
        System.out.println("Array length");
        int s = sausan.nextInt();
        int numb = 5;
        try {
            int[] except = new int[numb];
            checkArray(s, numb);
            for (int i = 0; i < s; i++) {
                except[i] = i = 1;
                System.out.println("Array index [" + i + "] = " + except[i]);
            }
        } catch (ArrayIndexOutOfBoundsException z) {
            System.out.println(z.getMessage());
        }
    }

    static int checkArray(int h, int m) {
        if (h > m) {
            throw new ArrayIndexOutOfBoundsException("Error");
        }
        return m - h;
    }
}


Download the file here
Share:

0 comments:

Posting Komentar