Вы находитесь на странице: 1из 38

PEMROGRAMAN LANJUT

Informatika FILKOM UB
Semester Genap 2015/2016

EXCEPTION HANDLING
Penanganan Pengecualian

Dr. Eng. Herman Tolle


Program Teknologi Informasi & Ilmu Komputer, Universitas Brawijaya
Outline Keyword

Run time error


Exception
Exception Handling
Try
Catch
Finally
Throw
Motivation
Program berjalan dengan lancar tanpa adanya
error atau bug.
Program yang baik adalah yang error-free
(bebas dari error)
Dapat mendeteksi kemungkinan kegagalan
(exception) dan mengatasi hal tersebut secara
otomatis
Type of Error
1. Compilation Error Syntax Error
2. Run Time Error Error when run a code
3. Logic / Algorithm Error Results Error
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.
5
Exception Classes
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
7
System Errors
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

System errors are thrown by JVM Several more classes


LinkageError
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely VirtualMachineError

occur. If one does, there is little Error


you can do beyond notifying the AWTError
user and trying to terminate the
program gracefully. Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
8
Exceptions
Exception describes errors ClassNotFoundException
caused by your program
and external IOException
circumstances. These ArithmeticException
errors can be caught and Exception AWTException
handled by your program. NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
9
Runtime Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError RuntimeException is caused by


Error programming errors, such as bad
casting, accessing an out-of-bounds
AWTError
array, and numeric errors.

Several more classes

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
10
RUN TIME ERROR

11
Run Time Error
Error yang terjadi saat program sedang berjalan
Jika pada saat program dijalankan, ada kondisi
yang tidak diinginkan (exception) terjadi, maka
program akan terminate (stop).
Exception yang terjadi biasanya karena
mengakses sesuatu yang tidak ada:
Mengakses indeks array diluar kapasitas
(ArrayIndexOutOfBound)
Mengakses file yang tidak ada
Pembagian dengan Nol
Konversi variabel dari tipe data tertentu
Exception Caused by
caused by user error salah input oleh user
by programmer error logic error, algortima
yang kurang tepat
by physical resources that have failed in some
manner akses file yang tidak ada
Runtime Errors
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.

Run

14
Try Throw - Catch

Use to
try, watch for
throw, indicate exceptions
catch handle

How to process exceptions and failures.

15
Catch Runtime Errors
1 import java.util.*; Run
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 boolean continueInput = true;
7
8 do {
9 try {
10 System.out.print("Enter an integer: ");
11 int number = scanner.nextInt();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is System.out.println(
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 System.out.println("Try again. (" +
21 "Incorrect input: an integer is required)");
22 scanner.nextLine(); // discard input
23 }
24 } while (continueInput);
25 }
13 }
16
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 dalam
konjungsi 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 penanganan
exception. Header dari blok catch harus membawa
satu argumen, dimana exception pada blok tersebut
akan ditangani.
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...
}
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 doesnt 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
public class ExcepTest{
public static void main(String args[]){
Contoh
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
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)
{
[...]
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)
{
// ...
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)
{
// ...
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
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
}
}
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;


}
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;
}
}
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.

}
Finally block Selalu dieksekusi
Sequence of Events for throw
Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

30
Sequence of Events for
No throw
Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

31
Sequence of Events for finally
clause
Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

finally

next step
32
Example 1: Arithmetic exception
Class: 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 Ive divided an integer by a zero and due to
which ArithmeticException is thrown.
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 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println (Exception: + e);
}
}
}
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");
}
}
}
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());
}
}
import java.io.BufferedReader; Example 5: Read File
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 file
System.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");
}
}
}
}
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

Вам также может понравиться