0% found this document useful (0 votes)
3 views1 page

Java Exception Handling Demos (1)

The document provides Java exception handling demos for two common exceptions: ArithmeticException and ArrayIndexOutOfBoundsException. The first demo illustrates handling a divide by zero error, while the second demonstrates handling an invalid array index access. Both examples include sample runs showing how the exceptions are caught and handled gracefully.

Uploaded by

Sujithkumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Java Exception Handling Demos (1)

The document provides Java exception handling demos for two common exceptions: ArithmeticException and ArrayIndexOutOfBoundsException. The first demo illustrates handling a divide by zero error, while the second demonstrates handling an invalid array index access. Both examples include sample runs showing how the exceptions are caught and handled gracefully.

Uploaded by

Sujithkumar S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Java Exception Handling Demos

1. Handle ArithmeticException (Divide by Zero)


// File: DivideByZeroDemo.java
import java.util.Scanner;

public class DivideByZeroDemo {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

try {
System.out.print("Enter dividend: ");
int dividend = sc.nextInt();

System.out.print("Enter divisor: ");


int divisor = sc.nextInt();

int result = dividend / divisor; // may throw ArithmeticException


System.out.println("Result = " + result);

} catch (ArithmeticException ex) {


System.out.println("■■ Cannot divide by zero. Details: " + ex);
} finally {
sc.close();
System.out.println("Program finished safely.");
}
}
}
Sample Run:
Enter dividend: 12
Enter divisor: 0
■■ Cannot divide by zero. Details: java.lang.ArithmeticException: / by zero
Program finished safely.
2. Handle ArrayIndexOutOfBoundsException
// File: ArrayIndexDemo.java
public class ArrayIndexDemo {
public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50};

try {
// Deliberately access an invalid index
System.out.println("Element at index 10 = " + numbers[10]);

} catch (ArrayIndexOutOfBoundsException ex) {


System.out.println("■■ Invalid array index. Details: " + ex);
}

System.out.println("Program continues after handling the exception.");


}
}
Sample Run:
■■ Invalid array index. Details: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for len
Program continues after handling the exception.

You might also like