0% found this document useful (0 votes)
25 views12 pages

CSW2 Assignment3 Soln

The document contains solutions for a series of Java programming assignments focused on error handling. Each assignment includes code examples that demonstrate handling various exceptions such as NullPointerException, NumberFormatException, and custom exceptions, along with practical scenarios like string manipulation, array operations, and file handling. The solutions emphasize the importance of robust error handling to ensure program stability and user-friendly error messages.

Uploaded by

komalmohanty05
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)
25 views12 pages

CSW2 Assignment3 Soln

The document contains solutions for a series of Java programming assignments focused on error handling. Each assignment includes code examples that demonstrate handling various exceptions such as NullPointerException, NumberFormatException, and custom exceptions, along with practical scenarios like string manipulation, array operations, and file handling. The solutions emphasize the importance of robust error handling to ensure program stability and user-friendly error messages.

Uploaded by

komalmohanty05
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/ 12

CSW2 ASSIGNMENT 3

(CHAPTER 14 – ERROR HANDLING)


SOLUTIONS
--------------------------------------------------------------------------------
1. You are given a string containing alphanumeric characters, and your task is to design
a Java program that extracts and displays the numeric characters from the given string.
If no numeric characters are present, the program should display an appropriate message
indicating their absence. Additionally, if the input string is null or empty, the program
must throw a NullPointerException with a meaningful error message.

package q1;
public class NullPointException {
public static void main(String[] args) {
String str1 = "Anindya2004";
String str2 = "Anindya";
String str3 = null;
try {
extractAndShowNumbers(str1);
extractAndShowNumbers(str2);
extractAndShowNumbers(str3);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
public static void extractAndShowNumbers(String input) {
if (input == null || input.isEmpty()) {
throw new NullPointerException("Input string cannot be null or
empty.");
}
StringBuilder numChar = new StringBuilder();
for (char ch : input.toCharArray()) {
if (ch >= '0' && ch <= '9') {
numChar.append(ch);
}
}
if (numChar.length() > 0) {
System.out.println("Numeric characters extracted: " +
numChar.toString());
} else {
System.out.println("No numeric characters found in the input
string.");
}
}
}

OUTPUT:

Numeric characters extracted: 2004


No numeric characters found in the input string.
Input string cannot be null or empty.

Prepared by MAJI, A.
2. Implement a custom exception class named CustomNullPointerException that
replicates the behavior of the standard NullPointerException. However, instead of relying
on default error messages or null references, this custom exception should accept a String
message as a constructor argument. Your task is to create this custom exception class and
demonstrate its usage in a Java program.

package q2;
class CustomNullPointerException extends Exception {
public CustomNullPointerException(String msg) {
super(msg);
}
}
public class CustomNullPointException {
public static void main(String[] args) {
try {
String str = null;
if (str == null) {
throw new CustomNullPointerException("Custom
NullPointerException: The value is null!");
}
} catch (CustomNullPointerException e) {
System.out.println(e.getMessage());
}
}
}

OUTPUT:

Custom NullPointerException: The value is null!

Prepared by MAJI, A.
3. Create a method that accepts a string input and converts it into an integer. Use a try-
catch block to handle NumberFormatException, and if an exception occurs, prompt the
user to enter a valid numeric value.

package q3;
import java.util.Scanner;
public class StringToIntegerConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter a numeric value: ");
int number = Integer.parseInt(sc.nextLine());
System.out.println("You entered the number: " + number);
break;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again.");
}
}
sc.close();
}
}

OUTPUT:

Enter a numeric value: abc123


Invalid input. Try again.
Enter a numeric value: 123
You entered the number: 123

Prepared by MAJI, A.
4. Write a Java program to find the square root of an integer number. Demonstrate the
use of a try-catch block to handle ArithmeticException.

package q4;
import java.util.Scanner;
public class SqRtCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer:");
try {
int num = sc.nextInt();
if (num < 0) {
throw new ArithmeticException("Cannot calculate the square root
of a negative number.");
}
double sqRt = Math.sqrt(num);
System.out.println("The square root of " + num + " is: " + sqRt);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
sc.close();
}
}
}

OUTPUT:

Enter a positive integer:-225


Error: Cannot calculate the square root of a negative number.
Enter a positive integer:225
The square root of 225 is: 15.0

Prepared by MAJI, A.
5. Demonstrate the use of a nested try-catch block. Write a Java program where the outer
try-catch block handles a NumberFormatException, while the inner try-catch block
handles an ArithmeticException.

package q5;
import java.util.Scanner;
public class NestedTryCatch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter two numbers: ");
String input1 = sc.next();
String input2 = sc.next();
try {
int num1 = Integer.parseInt(input1);
int num2 = Integer.parseInt(input2);
try {
int result = num1 / num2;
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format. Please enter valid
integers.");
}
sc.close();
}
}

OUTPUT:

Enter two numbers:


25
0
Error: Cannot divide by zero.

Enter two numbers:


256
a24
Error: Invalid number format. Please enter valid integers.

Enter two numbers:


256
8
Result of division: 32

Prepared by MAJI, A.
6. Implement a Java program that performs complex manipulations on an array of
integers, including operations such as sorting, searching, and accessing elements at
various indices. Introduce scenarios where accessing elements beyond the array bounds
leads to an ArrayIndexOutOfBoundsException. Handle these exceptions gracefully to
ensure the program continues execution without crashing.

package q6;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayManipulation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = {15, 8, 25, 5, 18, 30, 10};
System.out.println("Original Array: " + Arrays.toString(array));
Arrays.sort(array);
System.out.println("Sorted Array: " + Arrays.toString(array));
System.out.print("Enter an element to search: ");
int searchElement = sc.nextInt();
int searchIndex = Arrays.binarySearch(array, searchElement);
if (searchIndex >= 0) {
System.out.println("Element " + searchElement + " found at index: "
+ searchIndex);
} else {
System.out.println("Element " + searchElement + " not found in the
array.");
}
System.out.print("Enter an index to access: ");
int index = sc.nextInt();
try {
System.out.println("Element at index " + index + ": " +
array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access an index out of
bounds.");
}
System.out.println("Program execution completed!");
sc.close();
}
}

OUTPUT:

Original Array: [15, 8, 25, 5, 18, 30, 10]


Sorted Array: [5, 8, 10, 15, 18, 25, 30]
Enter an element to search: 18
Element 18 found at index: 4
Enter an index to access: 8
Error: Attempted to access an index out of bounds.
Program execution completed!

Prepared by MAJI, A.
7. Design a Java program to perform matrix operations such as addition, multiplication,
and transpose. Introduce scenarios where accessing elements beyond the matrix bounds
results in an ArrayIndexOutOfBoundsException. Handle these exceptions effectively and
provide meaningful error messages that clearly indicate the nature of the exception.

package q7;
public class MatrixOperations {
public static void main(String[] args) {
int[][] matrixA = {
{1, 2},
{3, 4}
};
int[][] matrixB = {
{5, 6},
{7, 8}
};
System.out.println("Matrix A:");
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
System.out.print(matrixA[i][j] + " ");
}
System.out.println();
}
System.out.println("Matrix B:");
for (int i = 0; i < matrixB.length; i++) {
for (int j = 0; j < matrixB[0].length; j++) {
System.out.print(matrixB[i][j] + " ");
}
System.out.println();
}
System.out.println("Matrix Addition:");
int[][] additionResult = new int[matrixA.length][matrixA[0].length];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
additionResult[i][j] = matrixA[i][j] + matrixB[i][j];
System.out.print(additionResult[i][j] + " ");
}
System.out.println();
}
System.out.println("Matrix Multiplication:");
int[][] multiplicationResult = new
int[matrixA.length][matrixB[0].length];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixB[0].length; j++) {
for (int k = 0; k < matrixA[0].length; k++) {
multiplicationResult[i][j] += matrixA[i][k] * matrixB[k][j];
}
System.out.print(multiplicationResult[i][j] + " ");
}
System.out.println();
}
System.out.println("Transpose of Matrix A:");
int[][] transposeA = new int[matrixA[0].length][matrixA.length];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
transposeA[j][i] = matrixA[i][j];
}
}
for (int i = 0; i < transposeA.length; i++) {
for (int j = 0; j < transposeA[0].length; j++) {
System.out.print(transposeA[i][j] + " ");
}
System.out.println();

Prepared by MAJI, A.
}
try {
System.out.println("Accessing an out-of-bounds element to
demonstrate exception handling:");
System.out.println(matrixA[2][2]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access elements beyond
matrix bounds. ");
}
}
}

OUTPUT:

Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
Matrix Addition:
6 8
10 12
Matrix Multiplication:
19 22
43 50
Transpose of Matrix A:
1 3
2 4
Accessing an out-of-bounds element to demonstrate exception handling:
Error: Attempted to access elements beyond matrix bounds.

Prepared by MAJI, A.
8. Create a custom-checked exception class named CustomCheckedException. Use this
exception in your program to handle a specific error condition and demonstrate its usage
with a try-catch block.

package q8;
class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
public class CustomException {
public static void main(String[] args) {
try {
checkValue(15);
} catch (CustomCheckedException e) {
System.out.println("Caught CustomCheckedException: " +
e.getMessage());
}
}
public static void checkValue(int value) throws CustomCheckedException {
if (value > 10) {
throw new CustomCheckedException("The value " + value + " exceeds
the allowed limit of 10.");
}
System.out.println("Value " + value + " is within the allowed limit.");
}
}

OUTPUT:

Caught CustomCheckedException: The value 15 exceeds the allowed limit of 10.

Prepared by MAJI, A.
9. Implement a method that reads an integer from the user and handles
InputMismatchException using a try-catch block.

package q9;
import java.util.InputMismatchException;
import java.util.Scanner;
public class InputMismatch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter an integer: ");
int num = sc.nextInt();
System.out.println("You entered: " + num);
break;
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a valid
integer.");
sc.next();
}
}
sc.close();
}
}

OUTPUT:

Enter an integer: a26


Invalid input! Please enter a valid integer.
Enter an integer: 26
You entered: 26

Prepared by MAJI, A.
10. Implement a Java program that reads a file path from the command-line argument
and attempts to read its contents. If the file path is null or points to a non-existent file,
throw a custom FileNotFoundException. If the file exists but cannot be read due to
permission issues, throw a custom FileReadPermissionException. Your task is to create
these custom exception classes and handle them appropriately in your program.

package q10;
import java.io.File;
import java.io.FileNotFoundException;
class FileReadPermissionException extends Exception {
public FileReadPermissionException(String message) {
super(message);
}
}
public class FileHandler {
public static void main(String[] args) {
try {
if (args.length == 0 || args[0] == null)
throw new FileNotFoundException("File path is null. Please
provide a valid file path.");
File file = new File(args[0]);
if (!file.exists())
throw new FileNotFoundException("File not found: " + args[0]);
if (!file.canRead())
throw new FileReadPermissionException("Permission denied: Cannot
read the file " + args[0]);
System.out.println("File exists and can be read: " + args[0]);
} catch (FileNotFoundException | FileReadPermissionException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

OUTPUT:

Error: File path is null. Please provide a valid file path.

Error: File not found: E:\CSW SOLUTION CODE FILES\CSW_ASSIGNMENT3_SOLN.docx

File exists and can be read: E:\CSW SOLUTION CODE


FILES\CSW2_ASSIGNMENT3_SOLN.docx

Prepared by MAJI, A.
11. Write a program that reads data from a file and performs some processing. Handle
checked IOException by using try-catch block to catch and handle the exception.

package q11;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileProcessor {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Processed: " + line.toUpperCase());
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

OUTPUT:

Error: example.txt (The system cannot find the file specified)

Prepared by MAJI, A.

You might also like