Materi Exception
Materi Exception
Objek I
Exception
Exception
Contoh Exception
1. public class DivByZero {
2. public static void main(String[] args) {
3.
int angka1 = 1;
4.
int angka2 = 0;
5.
int hasil = angka1/angka2;//Salah
6.
System.out.println("Hasil =" + hasil);
7. }
8. }
Didapatkan pesan kesalahan sebagai berikut :
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at DivByZero.main(DivByZero.java:5)
try {
<code to be monitored for exceptions>
} catch (<ExceptionType1> <ObjName>) {
<handler if ExceptionType1 occurs>
} ...
} finally {
<code to be executed before the try block ends>
}
Mengandung kode penanganan setelah penggunaan try dan catch
//bersambung
10
throw new
ArithmeticException(testing...);
12
16
class MultipleCatchError {
public static void main(String args[]){
try {
int a = 2/0;
System.out.println(a);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
17
User-Defined Exceptions
Membuat exceptions Anda sendiri
Membuat sebuah class yang extends terhadap RuntimeException atau class
Exception
Modifikasi class
Members dan constructors dapat ditambahkan pada class
Contoh:
18
User-Defined Exceptions
class TestHateString {
public static void main(String args[]) {
String input = "invalid input";
try {
if (input.equals("invalid input")){
throw new HateStringExp ();
}
System.out.println(input);
} catch (HateStringExp e) {
System.out.println(Eksepsi String!");
}
}
}
19
Referensi :
Sumber : Module JENI 1
20