Difference between revisions of "JAVA: Tipe Exception dengan Contoh"

From OnnoWiki
Jump to navigation Jump to search
(Created page with "Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. exceptions-in-java Built-in Exce...")
 
 
(9 intermediate revisions by the same user not shown)
Line 1: Line 1:
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.  
+
Java mendefinisikan beberapa jenis exception yang berhubungan dengan berbagai class libraries. Java juga memungkinkan pengguna untuk menentukan exception mereka sendiri.
  
exceptions-in-java
+
[[File:Exceptions-in-Java.png|center|300px|thumb]]
  
Built-in Exceptions
 
  
 +
==Built-in Exception==
 
   
 
   
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.  
+
Built-in exception adalah exception yang tersedia di Java libraries. Exception ini cocok untuk menjelaskan situasi error tertentu. Di bawah ini adalah daftar built-in exception yang penting di Java.
  
ArithmeticException  
+
* '''ArithmeticException''' - Itu dilemparkan ketika kondisi luar biasa telah terjadi dalam operasi aritmatika.
It is thrown when an exceptional condition has occurred in an arithmetic operation.
+
* '''ArrayIndexOutOfBoundsException''' - Itu dilemparkan untuk menunjukkan bahwa array telah diakses dengan indeks ilegal. Indeksnya negatif atau lebih besar dari atau sama dengan ukuran array.
ArrayIndexOutOfBoundsException  
+
* '''ClassNotFoundException''' - Exception ini dimunculkan ketika kita mencoba mengakses class yang definisinya tidak ditemukan
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
+
* '''FileNotFoundException''' - Exception ini muncul saat file tidak dapat diakses atau tidak terbuka.
ClassNotFoundException  
+
* '''IOException''' - Thrown ketika operasi input-output gagal atau terputus
This Exception is raised when we try to access a class whose definition is not found
+
* '''InterruptedException''' - Thrown ketika sebuah utas sedang menunggu, tidur, atau melakukan beberapa pemrosesan, dan terputus.
FileNotFoundException  
+
* '''NoSuchFieldException''' - Thrown ketika kelas tidak berisi bidang (atau variabel) yang ditentukan
This Exception is raised when a file is not accessible or does not open.
+
* '''NoSuchMethodException''' - Thrown saat mengakses method yang tidak ditemukan.
IOException  
+
* '''NullPointerException''' - Exception ini muncul saat merujuk ke anggota object null. Null tidak mewakili apa-apa
It is thrown when an input-output operation failed or interrupted
+
* '''NumberFormatException''' - Exception ini muncul ketika method tidak dapat mengubah string menjadi format numerik.
InterruptedException  
+
* '''RuntimeException''' - Ini mewakili Exception apa pun yang terjadi selama runtime.
It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
+
* '''StringIndexOutOfBoundsException''' - Thrown oleh method Class String untuk menunjukkan bahwa indeks negatif atau lebih besar dari ukuran string
NoSuchFieldException  
 
It is thrown when a class does not contain the field (or variable) specified
 
NoSuchMethodException  
 
It is thrown when accessing a method which is not found.
 
NullPointerException  
 
This exception is raised when referring to the members of a null object. Null represents nothing
 
NumberFormatException  
 
This exception is raised when a method could not convert a string into a numeric format.
 
RuntimeException  
 
This represents any exception which occurs during runtime.
 
StringIndexOutOfBoundsException  
 
It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string
 
Examples of Built-in Exception:
 
  
Arithmetic exception
 
  
// Java program to demonstrate ArithmeticException
+
Contoh dari Built-in Exception:
class ArithmeticException_Demo
+
 
{
+
==Arithmetic exception==
    public static void main(String args[])
+
 
    {
+
// Java program to demonstrate ArithmeticException
        try {
+
class ArithmeticException_Demo
            int a = 30, b = 0;
+
{
            int c = a/b;  // cannot divide by zero
+
    public static void main(String args[])
            System.out.println ("Result = " + c);
+
    {
        }
+
        try {
        catch(ArithmeticException e) {
+
            int a = 30, b = 0;
            System.out.println ("Can't divide a number by 0");
+
            int c = a/b;  // cannot divide by zero
        }
+
            System.out.println ("Result = " + c);
    }
+
        }
}
+
        catch(ArithmeticException e) {
 +
            System.out.println ("Can't divide a number by 0");
 +
        }
 +
    }
 +
}
 +
 
 
Output:  
 
Output:  
 +
Can't divide a number by 0
  
Can't divide a number by 0
+
==NullPointer Exception==
NullPointer Exception
+
 
 +
//Java program to demonstrate NullPointerException
 +
class NullPointer_Demo
 +
{
 +
    public static void main(String args[])
 +
    {
 +
        try {
 +
            String a = null; //null value
 +
            System.out.println(a.charAt(0));
 +
        } catch(NullPointerException e) {
 +
            System.out.println("NullPointerException..");
 +
        }
 +
    }
 +
}
  
//Java program to demonstrate NullPointerException
 
class NullPointer_Demo
 
{
 
    public static void main(String args[])
 
    {
 
        try {
 
            String a = null; //null value
 
            System.out.println(a.charAt(0));
 
        } catch(NullPointerException e) {
 
            System.out.println("NullPointerException..");
 
        }
 
    }
 
}
 
 
Output:
 
Output:
 +
NullPointerException..
  
NullPointerException..
+
==StringIndexOutOfBound Exception==
StringIndexOutOfBound Exception
+
 
 +
// Java program to demonstrate StringIndexOutOfBoundsException
 +
class StringIndexOutOfBound_Demo
 +
{
 +
    public static void main(String args[])
 +
    {
 +
        try {
 +
            String a = "This is like chipping "; // length is 22
 +
            char c = a.charAt(24); // accessing 25th element
 +
            System.out.println(c);
 +
        }
 +
        catch(StringIndexOutOfBoundsException e) {
 +
            System.out.println("StringIndexOutOfBoundsException");
 +
        }
 +
    }
 +
}
  
// Java program to demonstrate StringIndexOutOfBoundsException
 
class StringIndexOutOfBound_Demo
 
{
 
    public static void main(String args[])
 
    {
 
        try {
 
            String a = "This is like chipping "; // length is 22
 
            char c = a.charAt(24); // accessing 25th element
 
            System.out.println(c);
 
        }
 
        catch(StringIndexOutOfBoundsException e) {
 
            System.out.println("StringIndexOutOfBoundsException");
 
        }
 
    }
 
}
 
 
Output:  
 
Output:  
 +
StringIndexOutOfBoundsException
  
StringIndexOutOfBoundsException
+
==FileNotFound Exception==
FileNotFound Exception
+
 
 +
//Java program to demonstrate FileNotFoundException
 +
import java.io.File;
 +
import java.io.FileNotFoundException;
 +
import java.io.FileReader;
 +
  class File_notFound_Demo {
 +
 
 +
    public static void main(String args[])  {
 +
        try {
 +
 
 +
            // Following file does not exist
 +
            File file = new File("E://file.txt");
 +
 
 +
            FileReader fr = new FileReader(file);
 +
        } catch (FileNotFoundException e) {
 +
            System.out.println("File does not exist");
 +
        }
 +
    }
 +
}
  
//Java program to demonstrate FileNotFoundException
 
import java.io.File;
 
import java.io.FileNotFoundException;
 
import java.io.FileReader;
 
class File_notFound_Demo {
 
 
    public static void main(String args[])  {
 
        try {
 
 
            // Following file does not exist
 
            File file = new File("E://file.txt");
 
 
            FileReader fr = new FileReader(file);
 
        } catch (FileNotFoundException e) {
 
          System.out.println("File does not exist");
 
        }
 
    }
 
}
 
 
Output:
 
Output:
 +
File does not exist
  
File does not exist
+
==NumberFormat Exception==
NumberFormat Exception
+
 
 +
// Java program to demonstrate NumberFormatException
 +
class  NumberFormat_Demo
 +
{
 +
    public static void main(String args[])
 +
    {
 +
        try {
 +
            // "akki" is not a number
 +
            int num = Integer.parseInt ("akki") ;
 +
 
 +
            System.out.println(num);
 +
        } catch(NumberFormatException e) {
 +
            System.out.println("Number format exception");
 +
        }
 +
    }
 +
}
  
// Java program to demonstrate NumberFormatException
 
class  NumberFormat_Demo
 
{
 
    public static void main(String args[])
 
    {
 
        try {
 
            // "akki" is not a number
 
            int num = Integer.parseInt ("akki") ;
 
 
            System.out.println(num);
 
        } catch(NumberFormatException e) {
 
            System.out.println("Number format exception");
 
        }
 
    }
 
}
 
 
Output:
 
Output:
 +
Number format exception
 +
 +
==ArrayIndexOutOfBounds Exception==
  
Number format exception
+
// Java program to demonstrate ArrayIndexOutOfBoundException
ArrayIndexOutOfBounds Exception
+
class ArrayIndexOutOfBound_Demo
 +
{
 +
    public static void main(String args[])
 +
    {
 +
        try{
 +
            int a[] = new int[5];
 +
            a[6] = 9; // accessing 7th element in an array of
 +
                      // size 5
 +
        }
 +
        catch(ArrayIndexOutOfBoundsException e){
 +
            System.out.println ("Array Index is Out Of Bounds");
 +
        }
 +
    }
 +
}
  
// Java program to demonstrate ArrayIndexOutOfBoundException
 
class ArrayIndexOutOfBound_Demo
 
{
 
    public static void main(String args[])
 
    {
 
        try{
 
            int a[] = new int[5];
 
            a[6] = 9; // accessing 7th element in an array of
 
                      // size 5
 
        }
 
        catch(ArrayIndexOutOfBoundsException e){
 
            System.out.println ("Array Index is Out Of Bounds");
 
        }
 
    }
 
}
 
 
Output:  
 
Output:  
 +
Array Index is Out Of Bounds
 +
 +
==User-Defined Exceptions==
 +
 +
Terkadang, built-in exception di Java tidak dapat menggambarkan situasi tertentu. Dalam kasus seperti itu, pengguna juga dapat membuat exception yang disebut 'user-defined Exception'.
 +
 +
Langkah-langkah berikut diikuti untuk pembuatan user-defined Exception.
 +
 +
* Pengguna harus membuat exception class sebagai subclass dari Exception class. Karena semua exception adalah subkelas dari Exception class, pengguna juga harus menjadikan class-nya sebagai subclass Exception class. Ini dilakukan sebagai:
  
Array Index is Out Of Bounds
+
class MyException extends Exception
User-Defined Exceptions
 
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, user can also create exceptions which are called ‘user-defined Exceptions’.
 
  
Following steps are followed for the creation of user-defined Exception.  
+
* Kita dapat menulis konstruktor default di exception class sendiri.
  
The user should create an exception class as a subclass of Exception class. Since all the exceptions are subclasses of Exception class, the user should also make his class a subclass of it. This is done as:
+
MyException(){}
class MyException extends Exception
+
 
We can write a default constructor in his own exception class.
+
* Kita juga dapat membuat konstruktor berparameter dengan string sebagai parameter. Kita dapat menggunakan ini untuk menyimpan detail exception. Kita dapat memanggil konstruktor super class(Exception) dari ini dan mengirim string ke sana.
MyException(){}
+
 
We can also create a parameterized constructor with a string as a parameter.  
+
MyException(String str)
We can use this to store exception details. We can call super class(Exception) constructor from this and send the string there.  
+
{
MyException(String str)
+
    super(str);
{
+
}
  super(str);
+
 
}
+
* Untuk memunculkan exception user-defined type, kita perlu membuat object ke exception class dan membuangnya menggunakan throw clause, seperti:
To raise exception of user-defined type, we need to create an object to his exception class and throw it using throw clause, as:  
+
 
MyException me = new MyException(“Exception details”);
+
MyException me = new MyException(“Exception details”);
throw me;
+
throw me;
The following program illustrates how to create own exception class MyException.
+
 
Details of account numbers, customer names, and balance amounts are taken in the form of three arrays.
+
Program berikut mengilustrasikan cara membuat exception class MyException sendiri.
In main() method, the details are displayed using a for-loop. At this time, check is done if in any account the balance amount is less than the minimum balance amount to be apt in the account.
+
* Rincian nomor rekening, nama pelanggan, dan jumlah saldo diambil dalam bentuk tiga array.
If it is so, then MyException is raised and a message is displayed “Balance amount is less”.
+
* Dalam metode main(), detail ditampilkan menggunakan for-loop. Pada saat ini, pemeriksaan dilakukan jika di akun mana pun jumlah saldo kurang dari jumlah saldo minimum agar sesuai dengan akun.
 +
* Jika sudah, maka MyException dimunculkan dan muncul pesan “Balance amount is less”.
  
// Java program to demonstrate user defined exception
 
 
// This program throws an exception whenever balance
 
// amount is below Rs 1000
 
class MyException extends Exception
 
{
 
    //store account information
 
    private static int accno[] = {1001, 1002, 1003, 1004};
 
 
    private static String name[] =
 
                {"Nish", "Shubh", "Sush", "Abhi", "Akash"};
 
 
    private static double bal[] =
 
        {10000.00, 12000.00, 5600.0, 999.00, 1100.55};
 
 
    // default constructor
 
    MyException() {    }
 
 
    // parameterized constructor
 
    MyException(String str) { super(str); }
 
 
    // write main()
 
    public static void main(String[] args)
 
    {
 
        try  {
 
            // display the heading for the table
 
            System.out.println("ACCNO" + "\t" + "CUSTOMER" +
 
                                          "\t" + "BALANCE");
 
 
            // display the actual account information
 
            for (int i = 0; i < 5 ; i++)
 
            {
 
                System.out.println(accno[i] + "\t" + name[i] +
 
                                              "\t" + bal[i]);
 
 
                // display own exception if balance < 1000
 
                if (bal[i] < 1000)
 
                {
 
                    MyException me =
 
                      new MyException("Balance is less than 1000");
 
                    throw me;
 
                }
 
            }
 
        } //end of try
 
 
        catch (MyException e) {
 
            e.printStackTrace();
 
        }
 
    }
 
}
 
RunTime Error
 
  
  MyException: Balance is less than 1000
+
  // Java program to demonstrate user defined exception
    at MyException.main(fileProperty.java:36)
+
 
Output:  
+
// This program throws an exception whenever balance
 +
// amount is below Rs 1000
 +
class MyException extends Exception
 +
{
 +
    //store account information
 +
    private static int accno[] = {1001, 1002, 1003, 1004};
 +
 
 +
    private static String name[] =
 +
                  {"Nish", "Shubh", "Sush", "Abhi", "Akash"};
 +
 
 +
    private static double bal[] =
 +
          {10000.00, 12000.00, 5600.0, 999.00, 1100.55};
 +
 
 +
    // default constructor
 +
    MyException() {    }
 +
 
 +
    // parameterized constructor
 +
    MyException(String str) { super(str); }
 +
 
 +
    // write main()
 +
    public static void main(String[] args)
 +
    {
 +
        try  {
 +
            // display the heading for the table
 +
            System.out.println("ACCNO" + "\t" + "CUSTOMER" +
 +
                                            "\t" + "BALANCE");
 +
 
 +
            // display the actual account information
 +
            for (int i = 0; i < 5 ; i++)
 +
            {
 +
                System.out.println(accno[i] + "\t" + name[i] +
 +
                                                "\t" + bal[i]);
 +
 
 +
                // display own exception if balance < 1000
 +
                if (bal[i] < 1000)
 +
                {
 +
                    MyException me =
 +
                        new MyException("Balance is less than 1000");
 +
                    throw me;
 +
                }
 +
            }
 +
        } //end of try
 +
 
 +
        catch (MyException e) {
 +
            e.printStackTrace();
 +
        }
 +
    }
 +
  }
  
ACCNO    CUSTOMER    BALANCE
+
RunTime Error
1001    Nish    10000.0
 
1002    Shubh    12000.0
 
1003    Sush    5600.0
 
1004    Abhi    999.0
 
  
 +
  MyException: Balance is less than 1000
 +
    at MyException.main(fileProperty.java:36)
  
 +
Output: 
 +
 +
ACCNO    CUSTOMER    BALANCE
 +
1001    Nish    10000.0
 +
1002    Shubh    12000.0
 +
1003    Sush    5600.0
 +
1004    Abhi    999.0
  
 
==Referensi==
 
==Referensi==
  
 
* https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/
 
* https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/

Latest revision as of 08:20, 11 May 2022

Java mendefinisikan beberapa jenis exception yang berhubungan dengan berbagai class libraries. Java juga memungkinkan pengguna untuk menentukan exception mereka sendiri.

Exceptions-in-Java.png


Built-in Exception

Built-in exception adalah exception yang tersedia di Java libraries. Exception ini cocok untuk menjelaskan situasi error tertentu. Di bawah ini adalah daftar built-in exception yang penting di Java.

  • ArithmeticException - Itu dilemparkan ketika kondisi luar biasa telah terjadi dalam operasi aritmatika.
  • ArrayIndexOutOfBoundsException - Itu dilemparkan untuk menunjukkan bahwa array telah diakses dengan indeks ilegal. Indeksnya negatif atau lebih besar dari atau sama dengan ukuran array.
  • ClassNotFoundException - Exception ini dimunculkan ketika kita mencoba mengakses class yang definisinya tidak ditemukan
  • FileNotFoundException - Exception ini muncul saat file tidak dapat diakses atau tidak terbuka.
  • IOException - Thrown ketika operasi input-output gagal atau terputus
  • InterruptedException - Thrown ketika sebuah utas sedang menunggu, tidur, atau melakukan beberapa pemrosesan, dan terputus.
  • NoSuchFieldException - Thrown ketika kelas tidak berisi bidang (atau variabel) yang ditentukan
  • NoSuchMethodException - Thrown saat mengakses method yang tidak ditemukan.
  • NullPointerException - Exception ini muncul saat merujuk ke anggota object null. Null tidak mewakili apa-apa
  • NumberFormatException - Exception ini muncul ketika method tidak dapat mengubah string menjadi format numerik.
  • RuntimeException - Ini mewakili Exception apa pun yang terjadi selama runtime.
  • StringIndexOutOfBoundsException - Thrown oleh method Class String untuk menunjukkan bahwa indeks negatif atau lebih besar dari ukuran string


Contoh dari Built-in Exception:

Arithmetic exception

// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
    public static void main(String args[])
    {
        try {
            int a = 30, b = 0;
            int c = a/b;  // cannot divide by zero
            System.out.println ("Result = " + c);
        }
        catch(ArithmeticException e) {
            System.out.println ("Can't divide a number by 0");
        }
    }
}

Output:

Can't divide a number by 0

NullPointer Exception

//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
    public static void main(String args[])
    {
        try {
            String a = null; //null value
            System.out.println(a.charAt(0));
        } catch(NullPointerException e) {
            System.out.println("NullPointerException..");
        }
    }
}

Output:

NullPointerException..

StringIndexOutOfBound Exception

// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
    public static void main(String args[])
    {
        try {
            String a = "This is like chipping "; // length is 22
            char c = a.charAt(24); // accessing 25th element
            System.out.println(c);
        }
        catch(StringIndexOutOfBoundsException e) {
            System.out.println("StringIndexOutOfBoundsException");
        }
    }
}

Output:

StringIndexOutOfBoundsException

FileNotFound Exception

//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
 class File_notFound_Demo {
 
    public static void main(String args[])  {
        try {
 
            // Following file does not exist
            File file = new File("E://file.txt");
 
            FileReader fr = new FileReader(file);
        } catch (FileNotFoundException e) {
           System.out.println("File does not exist");
        }
    }
}

Output:

File does not exist

NumberFormat Exception

// Java program to demonstrate NumberFormatException
class  NumberFormat_Demo
{
    public static void main(String args[])
    {
        try {
            // "akki" is not a number
            int num = Integer.parseInt ("akki") ;
 
            System.out.println(num);
        } catch(NumberFormatException e) {
            System.out.println("Number format exception");
        }
    }
}

Output:

Number format exception

ArrayIndexOutOfBounds Exception

// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
    public static void main(String args[])
    {
        try{
            int a[] = new int[5];
            a[6] = 9; // accessing 7th element in an array of
                      // size 5
        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println ("Array Index is Out Of Bounds");
        }
    }
}

Output:

Array Index is Out Of Bounds

User-Defined Exceptions

Terkadang, built-in exception di Java tidak dapat menggambarkan situasi tertentu. Dalam kasus seperti itu, pengguna juga dapat membuat exception yang disebut 'user-defined Exception'.

Langkah-langkah berikut diikuti untuk pembuatan user-defined Exception.

  • Pengguna harus membuat exception class sebagai subclass dari Exception class. Karena semua exception adalah subkelas dari Exception class, pengguna juga harus menjadikan class-nya sebagai subclass Exception class. Ini dilakukan sebagai:
class MyException extends Exception
  • Kita dapat menulis konstruktor default di exception class sendiri.
MyException(){}
  • Kita juga dapat membuat konstruktor berparameter dengan string sebagai parameter. Kita dapat menggunakan ini untuk menyimpan detail exception. Kita dapat memanggil konstruktor super class(Exception) dari ini dan mengirim string ke sana.
MyException(String str)
{
   super(str);
}
  • Untuk memunculkan exception user-defined type, kita perlu membuat object ke exception class dan membuangnya menggunakan throw clause, seperti:
MyException me = new MyException(“Exception details”);
throw me;

Program berikut mengilustrasikan cara membuat exception class MyException sendiri.

  • Rincian nomor rekening, nama pelanggan, dan jumlah saldo diambil dalam bentuk tiga array.
  • Dalam metode main(), detail ditampilkan menggunakan for-loop. Pada saat ini, pemeriksaan dilakukan jika di akun mana pun jumlah saldo kurang dari jumlah saldo minimum agar sesuai dengan akun.
  • Jika sudah, maka MyException dimunculkan dan muncul pesan “Balance amount is less”.


// Java program to demonstrate user defined exception
 
// This program throws an exception whenever balance
// amount is below Rs 1000
class MyException extends Exception
{
    //store account information
    private static int accno[] = {1001, 1002, 1003, 1004};
 
    private static String name[] =
                 {"Nish", "Shubh", "Sush", "Abhi", "Akash"};
 
    private static double bal[] =
         {10000.00, 12000.00, 5600.0, 999.00, 1100.55};
 
    // default constructor
    MyException() {    }
 
    // parameterized constructor
    MyException(String str) { super(str); }
 
    // write main()
    public static void main(String[] args)
    {
        try  {
            // display the heading for the table
            System.out.println("ACCNO" + "\t" + "CUSTOMER" +
                                           "\t" + "BALANCE");
 
            // display the actual account information
            for (int i = 0; i < 5 ; i++)
            {
                System.out.println(accno[i] + "\t" + name[i] +
                                               "\t" + bal[i]);
 
                // display own exception if balance < 1000
                if (bal[i] < 1000)
                {
                    MyException me =
                       new MyException("Balance is less than 1000");
                    throw me;
                }
            }
        } //end of try
 
        catch (MyException e) {
            e.printStackTrace();
        }
    }
}

RunTime Error

 MyException: Balance is less than 1000
    at MyException.main(fileProperty.java:36)
Output:  

ACCNO    CUSTOMER    BALANCE
1001    Nish    10000.0
1002    Shubh    12000.0
1003    Sush    5600.0
1004    Abhi    999.0

Referensi