OOPS LAB 1
Name: ARYAN SAWANT
Reg No: 21BCE8189
Q1) WAP in java to implement Exception Handling using predefined exceptions.
ANS)
public class ExceptionHandlingDemo {
public static void main(String[] args) {
// Handling ArithmeticException
try {
int a = 10;
int b = 0;
int result = a / b; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
// Handling NullPointerException
try {
String str = null;
System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
// Handling ArrayIndexOutOfBoundsException
try {
int[] array = new int[5];
array[10] = 25; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
// Handling NumberFormatException
try {
String number = "abc";
int num = Integer.parseInt(number); // This will throw NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " + e.getMessage());
System.out.println("Program execution continues...");