Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ExceptionHandlingExample {
- public static void main(String[] args) {
- try {
- // Example 1: ArithmeticException (Runtime Exception)
- int result = 100 / 0;
- // Example 2: NullPointerException (Runtime Exception)
- String str = null;
- int length = str.length();
- // Example 3: ArrayIndexOutOfBoundsException (Runtime Exception)
- int[] arr = { 1, 2, 3 };
- int value = arr[3];
- // Example 4: FileNotFoundException (Compile-Time Exception)
- java.io.FileReader fileReader = new java.io.FileReader("non_existent_file.txt");
- // Example 5: NumberFormatException (Runtime Exception)
- String strNum = "abc123";
- int num = Integer.parseInt(strNum);
- } catch (ArithmeticException e) {
- System.out.println("ArithmeticException occurred: " + e.getMessage());
- } catch (NullPointerException e) {
- System.out.println("NullPointerException occurred: " + e.getMessage());
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println("ArrayIndexOutOfBoundsException occurred: " + e.getMessage());
- } catch (java.io.FileNotFoundException e) {
- System.out.println("FileNotFoundException occurred: " + e.getMessage());
- } catch (NumberFormatException e) {
- System.out.println("NumberFormatException occurred: " + e.getMessage());
- } catch (Exception e) {
- System.out.println("General Exception occurred: " + e.getMessage());
- } finally {
- System.out.println("Finally block executed.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement