ExceptionHandling Updated
ExceptionHandling Updated
Berorientasi Objek
Exception Handling
ExceptionHandling 2
Tujuan
• Dapat menjelaskan dengan baik mengenai konsep exception
handling.
• Dapat mengimplentasikan sejumlah exception handling untuk
mengatasi sejumlah exception yang mungkin terjadi pada suatu
program.
ExceptionHandling 3
Contoh kode program bermasalah (1)
javac Test.java
The local variable x may not have been initialized
ExceptionHandling 4
Contoh kode program bermasalah (2)
1 public class ExceptionExample {
2 public static void main(String[] args) {
3 String fileName = args[0];
4 System.out.println(args[0]);
5 System.out.println("Next instructions");
6 }
7 }
Runtime error
and Program is terminated!!
java ExceptionExample
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ExceptionExample.main(ExceptionExample.java:3)
ExceptionHandling 5
Contoh kode program bermasalah (3)
1 public class ExceptionExample2 {
2 public static void main(String[] args) {
3 String opsi = "1200 saja";
4 int total = 12 * Integer.parseInt(opsi);
5 System.out.println("Total: "+ total);
6 System.out.println("Next instructions");
7 }
8 }
java ExceptionExample2
Exception in thread "main" java.lang.NumberFormatException: For input string:
"1200 saja"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at ExceptionExample2.main(ExceptionExample2.java:4)
ExceptionHandling 6
Contoh kode program bermasalah (4)
javac Test.java
java Test
Objek tidak equal ketika di uji dengan operator ==
ExceptionHandling 7
Error dalam Program Komputer
• Error Tata Bahasa (Sintaks)
Kesalahan dalam penulisan tata bahasa suatu bahasa pemrograman.
Contohnya: kesalahan dalam penulisan kata kunci (reserverd word).
Paling mudah dideteksi karena masing-masing compiler atau interpreter suatu bahasa pemrograman akan
melakukan pengecekan jenis error ini sebelum program di jalankan/dieksekusi.
• Error Runtime
Error yang terjadi pada saat runtime, pada umumnya karena terjadi kesalahan dalam proses input, perhitungan
dan juga dalam proses output.
Contoh: error runtime karena pembagian suatu bilangan dengan nol.
ExceptionHandling 9
Exception vs Error Pada Java
• Exception:
– Kondisi yang terjadi saat runtime
yang dapat menyebabkan program
berhenti.
– Dapat ditangani oleh kode program
dan ekseskusi program dapat
dilanjutkan.
• Error:
– Kondisi yang sangat serius yang
terjadi pada saat runtime yang
menyebakan program berhenti.
– terjadi kesalahan pada Java Virtual
Machine, kesalahan yang
ditimbulkan oleh
environment/system (bukan berasal
dari program anda).
ExceptionHandling – Tidak dapat dihandle oleh program.10
Exception vs Error Pada Java
• Exception:
– Kondisi yang terjadi saat runtime
yang dapat menyebabkan program
berhenti.
– Dapat ditangani oleh kode program
dan ekseskusi program dapat
dilanjutkan.
• Error:
– Kondisi yang sangat serius yang
terjadi pada saat runtime yang
menyebakan program berhenti.
– terjadi kesalahan pada Java Virtual
Machine, kesalahan yang
ditimbulkan oleh
environment/system (bukan berasal
dari program anda).
ExceptionHandling – Tidak dapat dihandle oleh program.11
Exception Pada Java
• Tanpa Exception Handling
Sisa kode program
Kode program tanpa error Error
tidak dieksekusi
Eksekusi program berhenti
saat terjadi error
ExceptionHandling 12
Contoh kode program bermasalah (3)
1 public class ExceptionExample2 {
2 public static void main(String[] args) {
3 String opsi = "1200 saja";
4 int total = 12 * Integer.parseInt(opsi);
Kode program
5 System.out.println("Total: "+ total);
yang tidak
6 System.out.println("Next instructions");
dijalankan
7 }
8 }
java ExceptionExample2
Exception in thread "main" java.lang.NumberFormatException: For input string:
"1200 saja"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at ExceptionExample2.main(ExceptionExample2.java:4)
ExceptionHandling 13
Exception Pada Java
• Pada bahasa pemrograman prosedural, error handling
ditangani bersamaan dengan proses dalam program yang
dibuat (inline error handling ).
– Inline error handling: program sulit untuk dibaca, dimodifikasi,
debugging dan maintenance
• Pada Java, error handling dapat dilakukan bersamaan (inline)
atau terpisah dari kode program utama
ExceptionHandling 14
Exception Handling Fundamentals
- Exception Handling pada Java melibatkan 5 keyword penting:
try, catch, throw, throws, dan finally.
Bagaimana cara kerjanya?
Jika terjadi error - pada bagian
kode program yang dimonitor -
saat program sedang
dieksekusi…
Java run time system akan
membangkitkan suatu Java
Exception (objek)…
dan melemparkannya ke bagian
kode program yang bertugas
menanganani exception yang
terjadi.
ExceptionHandling 15
Contoh kode program bermasalah (2)
1 public class ExceptionExample {
2 public static void main(String[] args) { Mana bagian program yang
3 String fileName = args[0]; perlu di monitor pada blok
4 System.out.println(args[0]); try?
5 System.out.println("Next instructions");
6 }
7 }
java ExceptionExample
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ExceptionExample.main(ExceptionExample.java:3)
ExceptionHandling 16
How they work (1)
Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, an exception object is thrown by Java runtime system.
ExceptionHandling 19
Contoh kode program bermasalah (3)
1 public class ExceptionExample2 {
2 public static void main(String[] args) {
3 String opsi = "1200 saja";
4 int total = 12 * Integer.parseInt(opsi);
5 System.out.println("Total: "+ total);
6 System.out.println("Next instructions");
7 }
8 }
Coba tulis ulang kode program di
atas dengan exception handling
untuk menangani error yang
java ExceptionExample2 mungkin terjadi!
Exception in thread "main" java.lang.NumberFormatException: For input string:
"1200 saja"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at ExceptionExample2.main(ExceptionExample2.java:4)
ExceptionHandling 20
Contoh kode program bermasalah (4)
public class ExceptionHandlingExample2 {
public static void main(String[] args) {
String opsi = "1200 saja";
try{
int total = 12 * Integer.parseInt(opsi);
System.out.println("Total: "+ total); Apakah kode program
} ExceptionHandlingExample2
catch(NumberFormatException e ){ sudah benar?
System.out.println("Exception caught");
}
System.out.println("Next instruction");
}
}
ExceptionHandling 21
Contoh kode program bermasalah (4)
public class ExceptionHandlingExample2 {
public static void main(String[] args) {
String opsi = "1200 saja";
int total;
try{
total = 12 * Integer.parseInt(opsi); Apakah kode program
} ExceptionHandlingExample2
catch(NumberFormatException e ){ sudah benar?
System.out.println(“Exception caught");
}
System.out.println("Total: "+ total);
System.out.println("Next instruction");
}
}
> java ExceptionHandlingExample2
Exception caught
Next instructions
ExceptionHandling 22
Contoh kode program bermasalah (4)
public class ExceptionHandlingExample2 {
public static void main(String[] args) {
String opsi = "1200 saja";
int total;
try{
total = 12 * Integer.parseInt(opsi);
}
catch(NumberFormatException e ){
total = 12 * 100;
System.out.println(“Exception caught");
}
System.out.println("Total: "+ total);
System.out.println("Next instruction");
}
}> java ExceptionHandlingExample2
Exception caught
Next instructions
ExceptionHandling 23
1 class ExceptionHandlingExample3
2 { Another catch
3 public static void main(String[] args) {
4 String opsi = "1200 saja";
5 String fileName;
6 int total=0; >java ExeptionHandlingExample3 ini.txt
7 try{ //What is the result?
8 fileName = args[0];
9 System.out.println("File name " + args[0]);
10 total = 12 * Integer.parseInt(opsi);
11 } >java ExeptionHandlingExample3
12 catch(ArrayIndexOutOfBoundsException e){ //What is the result?
13 fileName ="test.txt"; //Code on line 10 is executed or not?
14 System.out.println("Exception1 caught"); //How if this code have to be executed?
15 System.out.println("File name " + fileName);
16 }
17 catch(NumberFormatException e ){
18 total = 1200;
>java ExeptionHandlingExample3 file1.txt
19 System.out.println("Exception2 caught");
//What is the result?
20 }
//Code on line 10 is executed or not?
21 catch(Exception g){
//How if this code have to be executed?
22 System.out.println("Exception3 caught");
23 }
24 System.out.println("Total: "+ total);
25 System.out.println("Next instructions :) ");
26 }
ExceptionHandling 24
27 }
1 class ExceptionHandlingExample3
2 { Another catch
3 public static void main(String[] args) {
>java ExeptionHandlingExample3 ini.txt
4 String opsi = "1200 saja";
5 String fileName;
File name ini.txt
6 int total=0; Exception2 caught
7 try{ Total: 1200
8 fileName = args[0]; Next instructions :)
9 System.out.println("File name " + args[0]);
10 total = 12 * Integer.parseInt(opsi);
11 }
12 catch(ArrayIndexOutOfBoundsException e){ >java ExeptionHandlingExample3
13 fileName ="test.txt"; Exception1 caught
14 System.out.println("Exception1 caught"); File name test.txt
15 System.out.println("File name " + fileName); Next instructions :)
16 } Perhatikan!!
17 catch(NumberFormatException e ){ Kode program ini tidak dieksekusi.
18 total = 1200;
19 System.out.println("Exception2 caught");
20 }
21 catch(Exception g){ >java ExeptionHandlingExample3 file1.txt
22 System.out.println("Exception3 caught"); File name file1.txt
23 } Exception2 caught
24 System.out.println("Total: "+ total); Total: 1200
25 System.out.println("Next instructions :) "); Next instructions :)
26 }
ExceptionHandling 25
27 }
1 class ExceptionHandlingExample3
2 { Another catch
3 public static void main(String[] args) {
>java ExeptionHandlingExample3 ini.txt
4 String opsi = "1200 saja";
5 String fileName;
File name ini.txt
6 int total=0; Exception2 caught
7 try{ Total: 1200
8 fileName = args[0]; Next instructions :)
9 System.out.println("File name " + args[0]);
10 }
11 catch(ArrayIndexOutOfBoundsException e){ >java ExeptionHandlingExample3
12 fileName ="test.txt"; Exception1 caught
13 System.out.println("Exception1 caught"); File name test.txt
14 System.out.println("File name " + fileName); Exception 2 caught
15 } catch(Exception g){S.o.p("Exception3 caught");} Total: 1200
16 try{ Next instructions :)
17 total = 12 * Integer.parseInt(opsi); Perhatikan!!
18 } Kode program ini dipindah ke blok try catch lain.
19 catch(NumberFormatException e ){
20 total = 1200;
21 System.out.println("Exception2 caught"); >java ExeptionHandlingExample3 file1.txt
22 } catch(Exception g){S.o.p("Exception3 caught");} File name file1.txt
23 System.out.println("Total: "+ total); Exception2 caught
24 System.out.println("Next instructions :) "); Total: 1200
25 } Next instructions :)
26 }
ExceptionHandling 26
Don’t Do This!
• Catching Exception
Using the most
general type.
Exception
IOException
FileNotFoundException
ExceptionHandling 27
How they work (2)
- Any code that absolutely must be executed before a method returns is put in
a finally block.
- The finally block is placed once (and only once) as the last block in a try/catch/finally statement.
>java ExeptionHandlingExample
public class ExceptionHandlingExample { Exception caught
public static void main(String[] args) {
File name test.txt
String filename;
try{
Always executed
fileName = args[0]; Next instruction :)
System.out.println("File name " + args[0]);
}
catch(ArrayIndexOutOfBoundsException e){
fileName ="test.txt";
System.out.println("Exception caught");
>java ExeptionHandlingExample test.txt
System.out.println("File name " + fileName);
} File name test.txt
finally{ Always executed
System.out.println("Always executed"); Next instruction :)
}
System.out.println("Next instructions :) ");
}
ExceptionHandling 28
}
The finally clause
• Exception will stop a method that currently being
executed ---> Dangerous!! FileReader reader = new FileReader(filename);
try
Example: {
Scanner in = new Scanner(reader);
reader = new FileReader(filename); readData(in);
Scanner in = new Scanner(reader); }
finally
readData(in); {
reader.close(); // May never get here reader.close();
// if an exception occurs, finally clause
// is also executed before exception
// is passed to its handler
• Has to execute reader.close() when an exception occurs }
• Use finally clause for code that must be executed
regardless the
circumstances
ExceptionHandling 29
The finally clause
• Dieksekusi ketika sebuah blok try dihentikan • Sebuah klausa finally selalu dieksekusi dengan
karena: alasan:
– Setelah statement terakhir pada blok try. – Blok try dieksekusi secara normal
– Setelah statement terakhir dari klausa catch, apabila – Klausa tersebut mengatur sebuah control flow
sebuah exception statement, seperti return, atau
terjadi. – Sebuah exception terjadi pada blok try
– Ketika sebuah exception terjadi, namun tidak ditangkap.
• Apabila sebuah blok finally memiliki alasan
• Gunakan klausa finally ketika ingin melakukan tersendiri untuk menghentikan sebuah program
pembersihan, misalkan menutup file, untuk (return, atau throwing
memastikan bahwa exception), alasan ia dieksekusi tidak akan terlihat.
sebuah file ditutup apapun yang terjadi.
ExceptionHandling 30
Try-catch-finally
class Aclass{
…
public void aMethod(){
try {
// Statements that might throw an exception
} catch (ErrorType1 e) {
// Handle ErrorType1 exceptions.
} catch (ErrorTypeN e) {
// Handle ErrorTypen exceptions.
} finally {
// This code always executes, no matter how the try block exits.
}
}
}
ExceptionHandling 31
Exception Pada Java
• Java Exception: object yang menggambarkan sebuah kondisi
eksepsional (exception) pada suatu bagian kode
• Saat terjadi exception, sebuah object yang mewakili exception
tersebut dibuat dan dilemparkan (thrown) dari method dimana
exception tersebut terjadi.
• Method tersebut dapat memilih untuk menghandle sendiri
exception tersebut atau melemparkannya pada yang lain.
ExceptionHandling 32
Exception Pada Java
• Exception dapat dihasilkan dari java run-time system maupun
dihasilkan secara manual dari kode program.
• Exception yang dihasilkan oleh Java biasanya terjadi karena
kesalahan dasar seperti melanggar ketentuan-ketentuan dari bahasa
pemrograman Java, pelanggaran pada batasan-batasan yang telah
didefinisikan didefinisikan dalam Java run Java run –time.
• Exception yang dihasilkan secara manual (generated by code)
digunakan untuk melaporkan atau menangkap exception yang
terjadi pada suatu method.
ExceptionHandling 33
How they work (3)
To manually throw an exception, use the keyword throw.
ExceptionHandling 34
How they work (4)
- Jika method yang mungkin menimbulkan exception tidak ingin menangani exception
yang terjadi gunakan throws.
- throws akan melempar keluar exception yang terjadi untuk ditangani oleh method lain.
RuntimeException IOException
NullPointerException EOFException
• Checked exceptions:
– Extends java.lang.Exception clas
– Client code has to handle the checked exceptions thrown by the API, either in a catch clause or
by forwarding it outward with the throws clause. If not, compile time error will happen.
• Unchecked exceptions:
– Extends java.lang.RuntimeException
– Unchecked Exception don't have to be caught or declared thrown. There is no requirement for
the client code to deal with them, and hence they are called unchecked exceptions.
ExceptionHandling 36
Hirarki Java Exception
ExceptionHandling 37
Unchecked Exception
ExceptionHandling 38
Checked Exception
ExceptionHandling 39
Checked Exception
ExceptionHandling 40
class SmallIntExcept extends Exception
{
private static int num_except; Make your own class
SmallIntExcept(String msg){
super(msg);
num_except++;
Exception
}
static int numException (){
return num_except; class SmallInt{
} int value;
void response (){ SmallInt(int val){
System.out.println value = val;
(getMessage()); }
} void plus(SmallInt X)throws SmallIntExcept{
} value = value + X.value;
if (value > 10)
throw (new SmallIntExcept ("TOO BIG"));
if (value < 0)
• Untuk membuat kelas exception throw (new SmallIntExcept ("TOO SMALL"));
}
sendiri perlu mengextend class public String toString() {
return Integer.toString(value);
Exception. }
void ReadVal () {
Scanner s = new Scanner(System.in);
value = s.nextInt();
}
ExceptionHandling 41
}
Main Program
class SmallIntTestDrive {
public static void main (String args[]) {
System.out.println("start of smallint ...");
SmallInt s1= new SmallInt(1);
SmallInt s = new SmallInt(2);
s.ReadVal ();
try {
s1.plus (s);
System.out.println("hasil S1= S1+S ="+s1);
}catch (SmallIntExcept e) {
e.response (); >java SmallIntTestDrive
} start of smallint ...
} 1
} Hasil S1= S1+S =2
>java SmallIntTestDrive
start of smallint ...
10
TOO BIG
ExceptionHandling 42
Latihan
ExceptionHandling 43
Latihan
ExceptionHandling 44
Referensi
ExceptionHandling 45