Advertisement
vvccs

E7_Exception_Handling

Nov 8th, 2023 (edited)
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. public class ExceptionHandlingExample {
  2.  
  3.     public static void main(String[] args) {
  4.         try {
  5.             // Example 1: ArithmeticException (Runtime Exception)
  6.             int result = 100 / 0;
  7.  
  8.             // Example 2: NullPointerException (Runtime Exception)
  9.             String str = null;
  10.             int length = str.length();
  11.  
  12.             // Example 3: ArrayIndexOutOfBoundsException (Runtime Exception)
  13.             int[] arr = { 1, 2, 3 };
  14.             int value = arr[3];
  15.  
  16.             // Example 4: FileNotFoundException (Compile-Time Exception)
  17.             java.io.FileReader fileReader = new java.io.FileReader("non_existent_file.txt");
  18.  
  19.             // Example 5: NumberFormatException (Runtime Exception)
  20.             String strNum = "abc123";
  21.             int num = Integer.parseInt(strNum);
  22.  
  23.         } catch (ArithmeticException e) {
  24.             System.out.println("ArithmeticException occurred: " + e.getMessage());
  25.         } catch (NullPointerException e) {
  26.             System.out.println("NullPointerException occurred: " + e.getMessage());
  27.         } catch (ArrayIndexOutOfBoundsException e) {
  28.             System.out.println("ArrayIndexOutOfBoundsException occurred: " + e.getMessage());
  29.         } catch (java.io.FileNotFoundException e) {
  30.             System.out.println("FileNotFoundException occurred: " + e.getMessage());
  31.         } catch (NumberFormatException e) {
  32.             System.out.println("NumberFormatException occurred: " + e.getMessage());
  33.         } catch (Exception e) {
  34.             System.out.println("General Exception occurred: " + e.getMessage());
  35.         } finally {
  36.             System.out.println("Finally block executed.");
  37.         }
  38.     }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement