document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. /**
  2.  * Contoh exception handling pada program pembagian.
  3.  *
  4.  * @author David Ralphwaldo Martuaraja
  5.  * @version 28 Desember 2020
  6.  */
  7.  
  8. import java.util.Scanner;
  9. import java.util.InputMismatchException;
  10.  
  11. public class ExceptionHandling
  12. {
  13.     public static void main(String[] args)
  14.     {
  15.         Scanner scanner = new Scanner(System.in);
  16.         boolean inputLoop1 = true, inputLoop2 = true;
  17.         int num1 = 0, num2 = 0;
  18.        
  19.         System.out.println("== Program pembagian sederhana ==");
  20.         System.out.println();
  21.        
  22.         do
  23.         {
  24.             try
  25.             {
  26.                 System.out.print("Masukkan angka pertama> ");
  27.                 num1 = scanner.nextInt();
  28.                 inputLoop1 = false;
  29.             } catch (InputMismatchException e) {
  30.                 System.err.println("Exception: " + e);
  31.                 System.out.println("Masukkan sebuah angka!");
  32.                 scanner.nextLine();
  33.             }
  34.         } while(inputLoop1);
  35.        
  36.         inputLoop1 = true;
  37.        
  38.         do
  39.         {
  40.             try
  41.                 {
  42.                 do
  43.                 {
  44.                     try
  45.                     {
  46.                         System.out.print("Masukkan angka kedua> ");
  47.                         num2 = scanner.nextInt();
  48.                         inputLoop1 = false;
  49.                     } catch (InputMismatchException e) {
  50.                         System.err.println("Exception: " + e);
  51.                         System.out.println("Masukkan sebuah angka!");
  52.                         scanner.nextLine();
  53.                     }
  54.                 } while(inputLoop1);
  55.                
  56.                 System.out.println("Hasil dari " + num1 + " / " + num2 + " = " + (num1 / num2));
  57.                 inputLoop2 = false;
  58.             } catch (ArithmeticException ae) {
  59.                 System.err.println("Exception: " + ae);
  60.                 System.out.println("Pembagian angka dengan nol!");
  61.                 scanner.nextLine();
  62.                
  63.                 inputLoop1 = true;
  64.             }
  65.         } while(inputLoop2);
  66.     }
  67. }
');