PL 09 ExceptionHandling
PL 09 ExceptionHandling
Informatika FILKOM UB
Semester Genap 2015/2016
EXCEPTION HANDLING
Penanganan Pengecualian
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
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
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
VirtualMachineError
Error
AWTError
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
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
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");
}
}}
Checked exceptions are defined using the throws keyword in the method
definition:
Since all Exception classes are a subclass of the Exception class, a catch
handler which catches "Exception" will catch all exceptions.
If you throw checked exceptions, you must indicate which exceptions your
method throws by using the throws keyword
if (anAmount>balance)
throw new InsuffientFundsException("Not enough cash");
}
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");
}
}
}
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;