0% found this document useful (0 votes)
3 views

Exception Handling

The document provides a series of Java programs demonstrating exception handling for various exceptions, including ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerException, and more. Each program includes a try-catch block to handle the specific exception and outputs a message when the exception is caught. The document serves as a comprehensive guide for understanding and implementing exception handling in Java.

Uploaded by

Ningamma Biradar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Exception Handling

The document provides a series of Java programs demonstrating exception handling for various exceptions, including ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerException, and more. Each program includes a try-catch block to handle the specific exception and outputs a message when the exception is caught. The document serves as a comprehensive guide for understanding and implementing exception handling in Java.

Uploaded by

Ningamma Biradar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Exception Handling

1. Write a program to handle ArrayIndexOutOfBoundsException


public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 50; // Index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
}
}
Output: Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of
bounds for length 5
2. Implement a program to handle ArithmeticException (division by zero).
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.ArithmeticException: / by zero

3. Write a program to handle NullPointerException.


public class NullPointerExceptionExample {
public static void main(String[] args) {
try {
String str = null;
str.length(); // Null pointer access
} catch (NullPointerException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.NullPointerException

4. Implement a program to handle FileNotFoundException.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileNotFoundExceptionExample {


Exception Handling

public static void main(String[] args) {


try {
File file = new File("nonexistentfile.txt");
Scanner scanner = new Scanner(file); // File not found
} catch (FileNotFoundException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.io.FileNotFoundException: nonexistentfile.txt (No such file or


directory)

5. Write a program to handle NumberFormatException.


public class NumberFormatExceptionExample {
public static void main(String[] args) {
try {
int num = Integer.parseInt("abc"); // Invalid number format
} catch (NumberFormatException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.NumberFormatException: For input string: "abc"

6. Implement a program to handle IOException.


import java.io.IOException;

public class IOExceptionExample {


public static void main(String[] args) {
try {
throw new IOException("I/O exception occurred");
} catch (IOException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.io.IOException: I/O exception occurred

7. Write a program to handle ClassNotFoundException.


public class ClassNotFoundExceptionExample {
public static void main(String[] args) {
try {
Class.forName("NonExistentClass"); // Class not found
} catch (ClassNotFoundException e) {
Exception Handling

System.out.println("Exception caught: " + e);


}
}
}

Output: Exception caught: java.lang.ClassNotFoundException: NonExistentClass

8. Implement a program to handle StackOverflowError.


public class StackOverflowErrorExample {
public static void main(String[] args) {
try {
recursiveMethod();
} catch (StackOverflowError e) {
System.out.println("Error caught: " + e);
}
}

public static void recursiveMethod() {


recursiveMethod(); // Stack overflow
}
}

Output: Error caught: java.lang.StackOverflowError

9. Write a program to handle NegativeArraySizeException.


public class NegativeArraySizeExceptionExample {
public static void main(String[] args) {
try {
int[] arr = new int[-5]; // Negative array size
} catch (NegativeArraySizeException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.NegativeArraySizeException

10. Implement a program to handle InterruptedException. public class InterruptedExceptionExample {

public static void main(String[] args) {

Thread thread = new Thread(() -> {

try {

Thread.sleep(1000); // Thread sleep

} catch (InterruptedException e) {

System.out.println("Exception caught: " + e);


Exception Handling

});

thread.start();

thread.interrupt(); // Interrupt the thread

Output: Exception caught: java.lang.InterruptedException: sleep interrupted

11.Write a program to handle ArrayStoreException.

public class ArrayStoreExceptionExample {

public static void main(String[] args) {

try {

Object[] arr = new Integer[5];

arr[0] = "String"; // Invalid type assignment

} catch (ArrayStoreException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.lang.ArrayStoreException: java.lang.String

12. Implement a program to handle IllegalStateException.

public class IllegalStateExceptionExample {

public static void main(String[] args) {

try {

throw new IllegalStateException("Illegal state encountered");

} catch (IllegalStateException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.lang.IllegalStateException: Illegal state encountered

13. Write a program to handle NoSuch Element Exception.

import java.util.*;

public class NoSuchElementExceptionExample {

public static void main(String[] args) {

try {

Scanner scanner = new Scanner(System.in);

scanner.nextLine(); // No input given

scanner.close();

} catch (NoSuchElementException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.NoSuchElementException

14. Implement a program to handle Unsupported OperationException.

import java.util.*;

public class UnsupportedOperationExceptionExample {

public static void main(String[] args) {

try {

List<String> list = Collections.emptyList();

list.add("Item"); // Unsupported operation

} catch (UnsupportedOperationException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.lang.UnsupportedOperationException

15. Write a program to handle Unsupported OperationException.

(same as above)

16. Implement a program to handle ConcurrentModificationException.

import java.util.*;

public class ConcurrentModificationExceptionExample {

public static void main(String[] args) {

try {

List<String> list = new ArrayList<>();

list.add("A");

list.add("B");

Iterator<String> iterator = list.iterator();

list.add("C"); // Modify list during iteration

iterator.next();

} catch (ConcurrentModificationException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.ConcurrentModificationException

17. Write a program to handle IllegalArgumentException.

public class IllegalArgumentExceptionExample {

public static void main(String[] args) {

try {

throw new IllegalArgumentException("Illegal argument");

} catch (IllegalArgumentException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.lang.IllegalArgumentException: Illegal argument

18. Implement a program to handle SecurityException.

public class SecurityExceptionExample {

public static void main(String[] args) {

try {

System.setSecurityManager(new SecurityManager());

System.exit(0); // Security exception thrown

} catch (SecurityException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.security.SecurityException: exit called from the security manager

19. Write a program to handle DateTimeParseException.

import java.time.LocalDate;

import java.time.format.DateTimeParseException;

public class DateTimeParseExceptionExample {

public static void main(String[] args) {

try {

LocalDate.parse("2025-01-32"); // Invalid date

} catch (DateTimeParseException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.time.format.DateTimeParseException: Text '2025-01-32' could not be


parsed at index 10

20. Implement a program to handle PatternSyntaxException.

import java.util.regex.*;

public class PatternSyntaxExceptionExample {

public static void main(String[] args) {

try {

Pattern.compile("["); // Invalid regular expression

} catch (PatternSyntaxException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.regex.PatternSyntaxException: Unclosed character class near index

21. Write a program to handle Missing ResourceException.

import java.util.*;

public class MissingResourceExceptionExample {

public static void main(String[] args) {

try {

ResourceBundle rb = ResourceBundle.getBundle("nonexistent");

} catch (MissingResourceException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.util.MissingResourceException: Can't find bundle for base name
nonexistent, locale en_US

22. Implement a program to handle Formatter ClosedException.

import java.util.*;

public class FormatterClosedExceptionExample {

public static void main(String[] args) {

try {

Formatter formatter = new Formatter();

formatter.close();

formatter.format("%s", "This will fail"); // Formatter closed

} catch (FormatterClosedException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.Formatter$FormatterClosedException

23. Write a program to handle Buffer OverflowException.

import java.nio.*;

public class BufferOverflowExceptionExample {

public static void main(String[] args) {

try {

ByteBuffer buffer = ByteBuffer.allocate(5);

buffer.put(new byte[10]); // Buffer overflow

} catch (BufferOverflowException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.nio.BufferOverflowException

24. Implement a program to handle Buffer UnderflowException.

import java.nio.*;

public class BufferUnderflowExceptionExample {

public static void main(String[] args) {

try {

ByteBuffer buffer = ByteBuffer.allocate(5);

buffer.get(new byte[10]); // Buffer underflow

} catch (BufferUnderflowException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.nio.BufferUnderflowException

25. Write a program to handle DateTimeException.

import java.time.*;

public class DateTimeExceptionExample {

public static void main(String[] args) {

try {

LocalTime time = LocalTime.of(25, 0); // Invalid hour

} catch (DateTimeException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 -
23): 25

You might also like