Difference between revisions of "JAVA: Cek & Uncek Exception di Java"

From OnnoWiki
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions:
+
Exception adalah peristiwa yang tidak diinginkan atau tidak terduga, yang terjadi selama pelaksanaan program yaitu pada waktu berjalan, yang mengganggu aliran normal instruksi program. Di Java, ada dua (2) jenis exception:
* Checked exceptions
+
* Checked exception
* Unchecked exceptions
+
* Unchecked exception
  
 +
[[File:Exception-in-java1.png|center|300px|thumb|Exception Hierarchy in Java]]
  
[[File:Exceptions-in-Java1.png|center|300px|thumb]]
 
  
 +
==Checked Exception==
  
==Checked Exceptions==
+
Ini adalah exception yang diperiksa pada waktu kompilasi. Jika beberapa code dalam suatu method melempar checked exception, maka method tersebut harus menangani exception atau harus menentukan exception menggunakan keyword throws.
  
These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword.
+
Sebagai contoh, perhatikan program Java berikut yang membuka file di lokasi "C:\test\a.txt" dan mencetak tiga baris pertama. Program tidak dapat dikompilasi, karena fungsi main() menggunakan FileReader() dan FileReader() throw checked exception FileNotFoundException. Itu juga menggunakan metode readLine() dan close() , dan metode ini juga throw exception yang diperiksa IOException
  
For example, consider the following Java program that opens the file at location “C:\test\a.txt” and prints the first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException
+
Contoh:
 
 
Example:
 
  
 
  // Java Program to Illustrate Checked Exceptions
 
  // Java Program to Illustrate Checked Exceptions
Line 46: Line 45:
 
Output:  
 
Output:  
  
 +
Untuk memperbaiki program di atas, kita perlu menentukan list exception menggunakan throw, atau kita perlu menggunakan blok try-catch. Kami telah menggunakan throw dalam program di bawah ini. Karena FileNotFoundException adalah subclass dari IOException, kita dapat menentukan IOException di list throw dan membuat program di atas bebas dari kesalahan kompiler.
  
 
+
Contoh:
To fix the above program, we either need to specify a list of exceptions using throws, or we need to use a try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.
 
 
 
Example:
 
  
 
  // Java Program to Illustrate Checked Exceptions
 
  // Java Program to Illustrate Checked Exceptions
Line 84: Line 81:
  
 
Output:  
 
Output:  
 +
First three lines of file "C:\test\a.txt"
  
First three lines of file "C:\test\a.txt"
+
==Unchecked Exceptions==
  
==Unchecked Exceptions==
+
Ini adalah exception yang tidak diperiksa pada waktu kompilasi. Di C++, semua exception tidak dipersiksa, sehingga tidak dipaksa oleh kompiler untuk menangani atau menentukan pengecualian. Terserah programmer untuk beradab, dan menentukan atau menangkap exception. Dalam Java exception di bawah Class Error dan RuntimeException adalah unchecked exception, semua yang lain di bawah throwable akan di cek.
  
These are the exceptions that are not checked at compile time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.  
+
Perhatikan program Java berikut. Ini mengkompilasi dengan baik, tetapi dia melempar ArithmeticException saat dijalankan. Kompiler mengizinkannya untuk dikompilasi karena ArithmeticException adalah unchecked exception.
  
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.
 
  
Example:
+
Contoh:
  
 
  // Java Program to Illustrate Un-checked Exceptions
 
  // Java Program to Illustrate Un-checked Exceptions
Line 118: Line 115:
 
     at Main.main(Main.java:5)
 
     at Main.main(Main.java:5)
 
  Java Result: 1
 
  Java Result: 1
 
  
  

Latest revision as of 08:39, 11 May 2022

Exception adalah peristiwa yang tidak diinginkan atau tidak terduga, yang terjadi selama pelaksanaan program yaitu pada waktu berjalan, yang mengganggu aliran normal instruksi program. Di Java, ada dua (2) jenis exception:

  • Checked exception
  • Unchecked exception
Exception Hierarchy in Java


Checked Exception

Ini adalah exception yang diperiksa pada waktu kompilasi. Jika beberapa code dalam suatu method melempar checked exception, maka method tersebut harus menangani exception atau harus menentukan exception menggunakan keyword throws.

Sebagai contoh, perhatikan program Java berikut yang membuka file di lokasi "C:\test\a.txt" dan mencetak tiga baris pertama. Program tidak dapat dikompilasi, karena fungsi main() menggunakan FileReader() dan FileReader() throw checked exception FileNotFoundException. Itu juga menggunakan metode readLine() dan close() , dan metode ini juga throw exception yang diperiksa IOException

Contoh:

// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException occured
  
// Importing I/O classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Reading file from path in local directory
        FileReader file = new FileReader("C:\\test\\a.txt");
  
        // Creating object as one of ways of taking input
        BufferedReader fileInput = new BufferedReader(file);
  
        // Printing first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++)
            System.out.println(fileInput.readLine());
  
        // Closing file connections
        // using close() method
        fileInput.close();
    }
}

Output:

Untuk memperbaiki program di atas, kita perlu menentukan list exception menggunakan throw, atau kita perlu menggunakan blok try-catch. Kami telah menggunakan throw dalam program di bawah ini. Karena FileNotFoundException adalah subclass dari IOException, kita dapat menentukan IOException di list throw dan membuat program di atas bebas dari kesalahan kompiler.

Contoh:

// Java Program to Illustrate Checked Exceptions
// Where FileNotFoundException does not occur
  
// Importing I/O classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
  
        // Creating a file and reading from local repository
        FileReader file = new FileReader("C:\\test\\a.txt");
  
        // Reading content inside a file
        BufferedReader fileInput = new BufferedReader(file);
  
        // Printing first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++)
            System.out.println(fileInput.readLine());
  
        // Closing all file connections
        // using close() method
        // Good practice to avoid any memory leakage
        fileInput.close();
    }
}

Output:

First three lines of file "C:\test\a.txt"

Unchecked Exceptions

Ini adalah exception yang tidak diperiksa pada waktu kompilasi. Di C++, semua exception tidak dipersiksa, sehingga tidak dipaksa oleh kompiler untuk menangani atau menentukan pengecualian. Terserah programmer untuk beradab, dan menentukan atau menangkap exception. Dalam Java exception di bawah Class Error dan RuntimeException adalah unchecked exception, semua yang lain di bawah throwable akan di cek.

Perhatikan program Java berikut. Ini mengkompilasi dengan baik, tetapi dia melempar ArithmeticException saat dijalankan. Kompiler mengizinkannya untuk dikompilasi karena ArithmeticException adalah unchecked exception.


Contoh:

// Java Program to Illustrate Un-checked Exceptions
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Here we are dividing by 0
        // which will not be caught at compile time
        // as there is no mistake but caught at runtime
        // because it is mathematically incorrect
        int x = 0;
        int y = 10;
        int z = y / x;
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.main(Main.java:5)
Java Result: 1


Referensi