JAVA ASS 4
JAVA ASS 4
Note: Attempt any two questions from the following [5 Marks Each]
Q1: Explain the concept of checked exceptions in Java. Provide examples of commonly
encountered checked exceptions and how they are handled.
Solution:
Checked exceptions in Java are exceptions that are checked at compile-time, meaning that the
compiler checks if the code handles these exceptions or declares them in the method signature.
Checked exceptions are typically used for situations that can be anticipated and recovered from,
such as le I/O errors or network connectivity issues.
Q2: Describe the use of multiple catch blocks for handling different types of exceptions in Java.
Provide an example scenario where it is necessary to handle multiple exceptions and explain
the order in which catch blocks are evaluated.
SOLUTION : Multiple catch blocks in Java allow developers to handle different types of exceptions
in a single try block. This approach enables more precise exception handling and provides better
error messages.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Assignment 4
# Using Multiple Catch Blocks:
```
try {
// Code that may throw exceptions
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
}
```
# Example Scenario:
Suppose we have a method that reads data from a le and performs some calculations. This
method may throw different types of exceptions, such as `FileNotFoundException`, `IOException`,
or `ArithmeticException`. We can use multiple catch blocks to handle these exceptions differently.
```
public void processData(String lename) {
try {
File le = new File( lename);
FileReader reader = new FileReader( le);
// Perform calculations that may throw ArithmeticException
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
}
}
```
# Best Practices:
1. *Handle speci c exceptions*: Handle speci c exceptions before general exceptions.
2. *Keep catch blocks concise*: Keep catch blocks concise and focused on handling the speci c
exception.
3. *Provide meaningful error messages*: Provide meaningful error messages to help diagnose and
resolve issues.
Note: Attempt any two questions from the following [10 Marks Each]
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Assignment 4
Q4: Describe the Java exception hierarchy. Differentiate between checked and unchecked
exceptions. Provide examples of each type of exception and explain when they might occur
during program execution.
SOLUTION : The Java exception hierarchy is a tree-like structure that categorizes exceptions into
different types. Here's an overview of the hierarchy and the differences between checked and
unchecked exceptions:
# Checked Exceptions:
- Checked at compile-time
- Must be handled using a `try-catch` block or declared in the method signature using the `throws`
keyword
- Typically used for situations that can be anticipated and recovered from, such as le I/O errors or
network connectivity issues
- Examples:
- `IOException`
- `FileNotFoundException`
- `SQLException`
# Unchecked Exceptions:
- Not checked at compile-time
- Typically used for programming errors or unexpected conditions that cannot be recovered from
- Subclasses of `Error` or `RuntimeException`
- Examples:
- `NullPointerException` (subclass of `RuntimeException`)
- `ArrayIndexOutOfBoundsException` (subclass of `RuntimeException`)
- `OutOfMemoryError` (subclass of `Error`)
# Best Practices:
1. *Handle checked exceptions*: Handle checked exceptions using `try-catch` blocks or declare
them in method signatures.
2. *Prevent unchecked exceptions*: Prevent unchecked exceptions by writing robust code that
checks for null references, array bounds, and other potential issues.
3. *Use exceptions judiciously*: Use exceptions judiciously and avoid using them for control ow or
normal program execution.
fi
fi
fl
Assignment 4
Q5: Develop a Java program that writes binary data to a le named "binary le.bin" using
FileOutputStream. Experiment with writing different types of binary data and explain the
importance of handling binary les.
SOLUTION: Here's an example Java program that writes binary data to a le named
"binary le.bin" using `FileOutputStream`:
// Write a boolean
boolean boolValue = true;
fos.write(boolValue ? 1 : 0);
} catch (IOException e) {
System.out.println("Error writing to le: " + e.getMessage());
}
}
}
```
# Best Practices:
1. *Use try-with-resources*: Use try-with-resources statements to ensure that les are properly
closed after use.
2. *Handle exceptions*: Handle exceptions that may occur during le I/O operations.
3. *Use consistent byte order*: Use a consistent byte order when writing binary data to les,
especially when working with multi-byte data types.
4. *Document le format*: Document the format of binary les, including the data types and byte
order used, to ensure that they can be read correctly.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Assignment 4
Note: Attempt any two questions from the following [20 Marks Each]
Q7: Extend the le reading program to include writing to a new le named "output.txt.
“ Implement exception handling to catch IOException during both reading and writing
operations.
SOLUTION: Here's an extended Java program that reads from a le, writes to a new le, and
includes exception handling for `IOException`:
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
System.out.println("An error occurred during le I/O: " + e.getMessage());
}
}
}
```
# Exception Handling:
1. *Try-with-resources*: The try-with-resources statement ensures that both the `BufferedReader`
and `BufferedWriter` are closed after use, regardless of whether an exception is thrown.
2. *Catch IOException*: The catch block catches `IOException` and prints an error message with
the exception's message.
# Best Practices:
1. *Handle speci c exceptions*: Handle speci c exceptions like `IOException` instead of catching
the general `Exception` class.
2. *Provide meaningful error messages*: Provide meaningful error messages to help diagnose and
resolve issues.
3. *Use try-with-resources*: Use try-with-resources statements to ensure that resources like les
are properly closed.
fi
fi
fi
fi
fi
fi
fi
fi
Assignment 4
Q8: Develop a Java program that demonstrates the handling of multiple exceptions. Include
scenarios such as le reading, arithmetic operations, and c
SOLUTION: Here's a Java program that demonstrates the handling of multiple exceptions:
// Arithmetic operation
int x = 10 / 0;
} catch (IOException e) {
System.out.println("An I/O error occurred: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("An arithmetic error occurred: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
}
}
}
```
However, the above code won't compile because the code after the rst exception (IOException)
won't be executed. Let's modify the code to handle each exception separately:
try {
// Arithmetic operation
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("An arithmetic error occurred: " + e.getMessage());
}
try {
// Array index out of bounds
int[] array = new int[5];
System.out.println(array[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
}
}
}
```
# Best Practices:
1. *Handle speci c exceptions*: Handle speci c exceptions instead of catching the general
`Exception` class.
2. *Keep try blocks small*: Keep try blocks small and focused on a speci c operation to make it
easier to handle exceptions.
3. *Provide meaningful error messages*: Provide meaningful error messages to help diagnose and
resolve issues.
By handling multiple exceptions and following best practices, developers can write robust and
reliable programs that handle potential errors and exceptions.
fi
fi
fi