Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap...

38
PEMROGRAMAN LANJUT Program Teknologi Informasi & Ilmu Komputer, Universitas Brawijaya EXCEPTION HANDLING Penanganan Pengecualian Dr. Eng. Herman Tolle Informatika FILKOM UB Semester Genap 2015/2016

Transcript of Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap...

Page 1: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

PEMROGRAMAN LANJUT

Program Teknologi Informasi & Ilmu Komputer, Universitas Brawijaya

EXCEPTION HANDLINGPenanganan Pengecualian

Dr. Eng. Herman Tolle

Informatika FILKOM UBSemester Genap 2015/2016

Page 2: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Outline Keyword

• Run time error

• Exception

• Exception Handling

• Try

• Catch

• Finally

• Throw

Page 3: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Motivation

• Program berjalan dengan lancar tanpa adanyaerror atau bug.

• Program yang baik adalah yang error-free (bebas dari error)

• Dapat mendeteksi kemungkinan kegagalan(exception) dan mengatasi hal tersebut secaraotomatis

Page 4: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Type of Error

1. Compilation Error Syntax Error

2. Run Time Error Error when run a code

3. Logic / Algorithm Error Results Error

Page 5: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

5

Syntax Errors, Runtime Errors, and Logic Errors

• Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler.

• Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out.

• Logic errors occur when a program doesn't perform the way it was intended to.

Page 6: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok
Page 7: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All

rights reserved. 0-13-222158-67

Exception Classes

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

Page 8: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All

rights reserved. 0-13-222158-68

System Errors

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

System errors are thrown by JVM

and represented in the Error class.

The Error class describes internal

system errors. Such errors rarely

occur. If one does, there is little

you can do beyond notifying the

user and trying to terminate the

program gracefully.

Page 9: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All

rights reserved. 0-13-222158-69

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

Exceptions

Exception describes errors

caused by your program

and external

circumstances. These

errors can be caught and

handled by your program.

Page 10: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All

rights reserved. 0-13-222158-610

Runtime Exceptions

LinkageError

Error

AWTError

AWTException

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Several more classes

Several more classes

Several more classes

IllegalArgumentException

RuntimeException is caused by

programming errors, such as bad

casting, accessing an out-of-bounds

array, and numeric errors.

Page 11: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

RUN TIME ERROR

11

Page 12: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Run Time Error

• Error yang terjadi saat program sedang berjalan

• Jika pada saat program dijalankan, ada kondisiyang tidak diinginkan (exception) terjadi, makaprogram akan terminate (stop).

• Exception yang terjadi biasanya karenamengakses sesuatu yang tidak ada:– Mengakses indeks array diluar kapasitas

(ArrayIndexOutOfBound)

– Mengakses file yang tidak ada

– Pembagian dengan Nol

– Konversi variabel dari tipe data tertentu

Page 13: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Exception Caused by

• caused by user error salah input oleh user

• by programmer error logic error, algortimayang kurang tepat

• by physical resources that have failed in some manner akses file yang tidak ada

Page 14: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

14

Runtime Errors

import java.util.Scanner;

public class ExceptionDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");

int number = scanner.nextInt();

// Display the result

System.out.println(

"The number entered is " + number);

}

}

If an exception occurs on this

line, the rest of the lines in the

method are skipped and the

program is terminated.

Terminated.

1

2

3

4

5

6

7

8

9

10

11

12

13

Run

Page 15: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

15

Try – Throw - Catch

Use

try,throw,

catch

to

watch forindicate exceptionshandle

How to process exceptions and failures.

Page 16: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

16

Catch Runtime Errors

import java.util.*;

public class HandleExceptionDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

boolean continueInput = true;

do {

try {

System.out.print("Enter an integer: ");

int number = scanner.nextInt();

// Display the result

System.out.println(

"The number entered is " + number);

continueInput = false;

}

catch (InputMismatchException ex) {

System.out.println("Try again. (" +

"Incorrect input: an integer is required)");

scanner.nextLine(); // discard input

}

} while (continueInput);

}

}

If an exception occurs on this line,

the rest of lines in the try block are

skipped and the control is

transferred to the catch block.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

13

Run

Page 17: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Block Try-Catch-Finally

• Notasi blok bersifat perintah

• Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally.

• Blok catch dan blok finally harus selalu muncul dalamkonjungsi dengan blok try, dan diatas urutan

• Blok try harus diikuti oleh paling sedikit satu blok catch ATAU satu blok finally, atau keduanya.

• Setiap blok catch mendefinisikan sebuah penangananexception. Header dari blok catch harus membawasatu argumen, dimana exception pada blok tersebutakan ditangani.

Page 18: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Exceptions -Syntax

try

{

// Code which might throw an exception

}

catch(FileNotFoundException x)

{

// code to handle a FileNotFound exception

}

catch(IOException x)

{

// code to handle any other I/O exceptions

}

catch(Exception x)

{

// Code to catch any other type of exception

}

finally

{

// This code is ALWAYS executed whether an exception was thrown

// or not. A good place to put clean-up code. ie. close

// any open files, etc...

}

Page 19: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Execution of try catch blocks• For normal execution:

– try block executes, then finally block executes, then other statements execute

• When an error is caught and the catch block throws an exception or returns:– try block is interrupted– catch block executes (until throw or return statement)– finally block executes

• When error is caught and catch block doesn’t throw an exception or return:– try block is interrupted– catch block executes– finally block executes– other statements execute

• When an error occurs that is not caught:– try block is interrupted– finally block executes

Page 20: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Contohpublic class ExcepTest{

public static void main(String args[]){

int a[] = new int[2];

try {

System.out.println("Access element three :" + a[3]);

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Exception thrown :" + e);

}

finally

{

a[0] = 6;

System.out.println("First element value: " +a[0]);

System.out.println("The finally statement is executed");

}

}}

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed

Page 21: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Exceptions -Defining checked exceptions

Any code which throws a checked exception MUST be placed within a try

block.

Checked exceptions are defined using the throws keyword in the method

definition:

public class PrintReader extends Reader

{

public int read() throws IOException

[...]

public void method1()

{

PrintReader aReader;

[... initialize reader ...]

try

{

int theCharacter = aReader.read();

}

catch(IOException x)

{

[...]

Page 22: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Exceptions -throwing multiple exceptions

A Method can throw multiple exceptions.

Multiple exceptions are separated by commas after the throws keyword:

public class MyClass

{

public int computeFileSize()

throws IOException, ArithmeticException

[...]

public void method1()

{

MyClass anObject = new MyClass();

try

{

int theSize = anObject.computeFileSize();

}

catch(ArithmeticException x)

{

// ...

}

catch(IOException x)

{

// ...

Page 23: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Exceptions -catching multiple exceptions

Each try block can catch multiple exceptions.

Start with the most specific exceptions

FileNotFoundException is a subclass of IO Exception

It MUST appear before IOException in the catch list

public void method1()

{

FileInputStream aFile;

try

{

aFile = new FileInputStream(...);

int aChar = aFile.read();

//...

}

catch(FileNotFoundException x)

{

// ...

}

catch(IOException x)

{

// ...

Page 24: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Exception -The catch-all Handler

Since all Exception classes are a subclass of the Exception class, a catch

handler which catches "Exception" will catch all exceptions.

It must be the last in the catch List

public void method1()

{

FileInputStream aFile;

try

{

aFile = new FileInputStream(...);

int aChar = aFile.read();

//...

}

catch(IOException x)

{

// ...

}

catch(Exception x)

{

// Catch All Exceptions

Page 25: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

The finally block

public void method1()

{

FileInputStream aFile;

try

{

aFile = new FileInputStream(...);

int aChar = aFile.read();

//...

}

catch(IOException x)

{

// ...

}

catch(Exception x)

{

// Catch All other Exceptions

}

finally

{

try

{

aFile.close();

}

catch (IOException x)

{

// close might throw an exception

}

}

Page 26: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Throwing Exceptions

You can throw exceptions from your own methods

To throw an exception, create an instance of the exception class and

"throw" it.

If you throw checked exceptions, you must indicate which exceptions your

method throws by using the throws keyword

public void withdraw(float anAmount) throws InsufficientFundsException

{

if (anAmount<0.0)

throw new IllegalArgumentException("Cannot withdraw negative amt");

if (anAmount>balance)

throw new InsuffientFundsException("Not enough cash");

balance = balance - anAmount;

}

Page 27: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Re-throwing Exceptions

If you catch an exception but the code determines it cannot reasonably

handle the exception, it can be rethrown:

public void addURL(String urlText) throws MalformedURLException

{

try

{

URL aURL = new URL(urlText);

// ...

}

catch(MalformedURLException x)

{

// determine that the exception cannot be handled here

throw x;

}

}

Page 28: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Automatically Passing Exceptions

If your method is defined to throw an exception, you need not catch it

within your method

public void addURL(String urlText) throws MalformedURLException

{

URL aURL = new URL(urlText);

// if the above throws a MalformedURLException, we need not have

// a try/catch block here because the method is defined to

// throw that exception. Any method calling this method MUST

// have a try/catch block which catches MalformedURLExceptions.

// Control is automatically transferred to that catch block.

}

Page 29: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Finally block Selalu dieksekusi

Page 30: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

30

Sequence of Events for throw

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

Page 31: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

31

Sequence of Events for No throw

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

Page 32: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

32

Sequence of Events for finally clause

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

finally

Page 33: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Example 1: Arithmetic exceptionClass: Java.lang.ArithmeticException

This is a built-in-class present in java.lang package. This exception occurs when

an integer is divided by zero.

class ExceptionDemo1 { public static void main(String args[]) {

try {

int num1=30, num2=0; int output=num1/num2; System.out.println ("Result = " +output);

} catch(ArithmeticException e){

System.out.println ("Arithmetic Exception: You can't divide an integer by 0"); }

}}

Output of above program:Arithmetic Exception: You can't divide an integer by 0

Explanation: In the above example I’ve divided an integer by a zero and due to

which ArithmeticException is thrown.

Page 34: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Example 2: ArrayIndexOutOfBounds Exception

Class: Java.lang.ArrayIndexOutOfBoundsException

This is a built in class present in java.lang package. This exception occurs when the referenced element does not exist in the array. For e.g. If array is having only 5 elements and we are trying to display 7th element then it would throw this exception.

Example:

class ExceptionDemo2 { public static void main(String args[]) { try { int a[]=new int[10]; //Array has only 10 elementsa[11] = 9;

} catch(ArrayIndexOutOfBoundsException e){ System.out.println (“Exception: “ + e);

}}

}

Page 35: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Example 3: NumberFormat Exception

class ExceptionDemo3{ public static void main(String args[]) { try {

int num=Integer.parseInt ("XYZ") ; System.out.println(num);

}catch(NumberFormatException e){

System.out.println("Number format exception occurred"); }

}}

Page 36: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

Example 4: Throw Exception

class MyOwnException extends Exception { public MyOwnException(String msg) { super(msg);

} }

class EmployeeTest { static void employeeAge(int age) throws MyOwnException { if(age < 0) throw new MyOwnException(“Umur tidak boleh kurang dari 0"); else System.out.println("Input Umur sudah sesuai");

} public static void main(String[] args) {

try { employeeAge(-2);

} catch (MyOwnException e) { System.out.println(“Error: “ + e.getMessage());

} }

Page 37: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;

public class ReadFileDemo { public static void main(String[] args) {

BufferedReader br = null; BufferedReader br2 = null; try {

br = new BufferedReader(new FileReader(“C:\\myfile.txt")); //reading the fileSystem.out.println("Reading the file using readLine() method:"); String contentLine = br.readLine(); while (contentLine != null) {

System.out.println(contentLine); contentLine = br.readLine();

} catch (IOException ioe) { ioe.printStackTrace(); } finally{

try { if (br != null) br.close();

} catch (IOException ioe) {

System.out.println("Error in closing the BufferedReader"); }

}}

}

Example 5: Read File

Page 38: Informatika FILKOM UB Semester Genap 2015/2016 … · •Notasi blok bersifat perintah •Setiap blok try, terdapat satu atau lebih blok catch, tetapi hanya satu blok finally. •Blok

LATIHAN

• Buat sebuah program untuk membaca file teks yang berisi teks sbb:

• NAMA NIP Gaji (Isikan min 3 data )

• Buat blok TRY-CATCH-FINALLY untuk mendeteksi file, membaca file & menutup file

• Jalankan program dan capture screenshot untuk 2 skenario:– File tidak dapat diakses

– File dapat diakses