About Exception Handling (AEH)


AEH:   SOLD       




Errors in a program often appear, even though the program is made by a highly skilled programmer. To avoid wasting time on the error-finding process, Java provides an exception handling mechanism. Exception is short for Exceptional Events. According to the general definition, an exception is an abnormal condition that occurs at runtime. Runtime errors or errors that occur while the program is running are realized and exceptions. Exceptions can be generated automatically by the Java runtime system or we can intentionally create them through certain statements for certain purposes.

Pay attention to the following program code:

public class DivByZero {
  public static void main(String args[]) {     int a = 5, b = 0, c;     c = a/b;

    System.out.println("c = " + c);
  }
}

The program code above is not syntactically wrong. However, there is a fatal error, namely division by 0. That is a = 5 divided by b = 0. Errors like this often occur because they are not obvious if we are not careful. If we compile the program code, the compilation will be successful. However, if we run it, we will not get any results but the program will display a message that an exception or abnormal condition has occurred (Figure 8.8) and the program will stop.


Figure 8.8. Warning of an error occurring

The message in Figure 8.8 informs the type of exception that occurred on the line where the exception originated. This is the default action that occurs when an unhandled exception occurs. If there is no code that handles the exception that occurs, the default action will run automatically.

Some common exception types include:

  • ArithmeticException. Exception due to errors related to calculations, for example division by 0.
  • ArrayIndexOutOfBoundException. Exception due to reading an array index outside the specified bounds. 
  • NullPointerException. Error due to pointer that does not contain (null) 
  • And others

1. Try and Catch 

Try is used to create a block containing statements that may cause an exception. If an exception occurs during the execution of the statements in the block, the exception will be thrown to the exception catcher block created with the catch keyword. Consider the following example.

Example 8.15. Exception with try-catch

public class DivByZero {
  public static void main(String args[]) {     int a = 5, b = 0, c;

    try {       c = a/b;     } catch (ArithmeticException exc) {
        //Reaksi jika terjadi exception
        System.out.println(exc);
    }
    System.out.println("Setelah exception");
  }
}

The program code in example 8.15 is a development of the previous program code. The statement c = a/b is a statement that we test whether it contains an exception or not. If an exception occurs, the exception will be thrown to the catch section. The exception that we check is ArithmeticException. The reaction that appears if an exception occurs is to run the System.out.println(exc); statement. With this mechanism, the program will not be forced to stop and the command after the try-catch block can still be executed. Figure 8.9 shows the results of executing the program code above. Compare with Figure 8.8.


Figure 8.9. Output from try-catch

Generally, there is more than one exception in one problem. In the following example 8.16, we use several types of exceptions to check for possible exceptions. Type the following program code and then run it and observe what happens.

Example 8.16. Exception with try-catch

class BanyakEksepsi {    public static void test(int a, int b) {     try {       int c = a / b;
      System.out.println("Hasil bagi: " + c);

      int[] Arr = {1,2,3,4,5};  // array dengan 5 elemen
      Arr[10] = 11;  // mengakses indeks ke-10
    } catch (ArithmeticException ae) {
      System.out.println("Terdapat pembagian dengan 0");
      System.out.println(ae);
    } catch (ArrayIndexOutOfBoundsException oobe) {
      System.out.println("Indeks di luar rentang");
      System.out.println(oobe);
    }
  }

  public static void main(String[] args) {

    test(4, 0);  // menimbulkan ArithmeticException
    System.out.println();

    test(12,  4);  //  menimbulkan
ArrayIndexOutOfBoundsException
  }
}

2. Throw 

In addition to catching exceptions, Java also allows a user to throw an exception. Consider Example 8.17 below.

Example 8.17. Exception with try-catch and throw

class ThrowDemo {
  public static void main(String args[]){     String input = "Salah input";
    try {
      if (input.equals("Salah input")) {
        throw  new
RuntimeException("Demonstrasi Throw");
      } else {
        System.out.println(input);
      }
      System.out.println("Setelah throw");
      } catch (RuntimeException e) {         System.out.println("Exception
ditangkap di sini.");
        System.out.println(e);
    }
  }
}

Pay attention to the statement that starts from the if command. If interpreted, the statement is if the value of the input variable is equal to "Incorrect input" then throw an exception by displaying "Throw Demonstration". The output of this program code will look like Figure 8.10.


Figure 8.10. Program output with throw

3. Finally 

The finally block contains the handling code after using try and catch. This code block is always executed no matter what happens in the try block. This code block will also produce a true value even if return, continue or break are executed. Consider the following program code.

Example 8.18. Exception with try-catch-finally

class DemoFinally {         private static int i = 0;

  public static void main(String[] args) {         while (true) {       try {
        System.out.print("Pada saat i = " + i + ": ");         if (i++ == 0) {
          throw new Exception();  // melempar exception
        }
        System.out.println("Tidak terjadi exception");
   } catch (Exception e) {
        System.out.println("Terdapat exception");
   } finally {
        System.out.println("Pernyataan  dalam  blok finally\n");         if (i == 2) {
          break;  // pada saat i==2, pengulangan akan berhenti         }
      }
    }
  }
}

When the program code is run, it will look like Figure 8.11. Note that what is in the finally code block will always be executed.


Figure 8.11. Output try-catch-finally program code


Post a Comment

Previous Next

نموذج الاتصال