0% found this document useful (0 votes)
2 views7 pages

JAVA ASS 4

The document discusses various aspects of exception handling in Java, focusing on checked and unchecked exceptions, the use of multiple catch blocks, and the Java exception hierarchy. It provides examples of common exceptions, best practices for handling exceptions, and includes sample Java programs demonstrating file I/O operations and handling multiple exceptions. The content emphasizes the importance of proper exception handling to ensure robust and reliable code.
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)
2 views7 pages

JAVA ASS 4

The document discusses various aspects of exception handling in Java, focusing on checked and unchecked exceptions, the use of multiple catch blocks, and the Java exception hierarchy. It provides examples of common exceptions, best practices for handling exceptions, and includes sample Java programs demonstrating file I/O operations and handling multiple exceptions. The content emphasizes the importance of proper exception handling to ensure robust and reliable code.
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/ 7

Assignment 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.

# Characteristics of Checked Exceptions:


1. *Inheritance*: Checked exceptions inherit from the `Exception` class (excluding
`RuntimeException`).
2. *Compile-time checking*: The compiler checks if the code handles checked exceptions or
declares them in the method signature.
3. *Handling*: Checked exceptions must be handled using a `try-catch` block or declared in the
method signature using the `throws` keyword.

# Commonly Encountered Checked Exceptions:


1. *IOException*: Thrown when there is an input/output error, such as reading or writing to a le.
2. *FileNotFoundException*: Thrown when a le is not found.
3. *SQLException*: Thrown when there is an error accessing a database.
4. *ParseException*: Thrown when there is an error parsing a string or le.

# Handling Checked Exceptions:


*Using Try-Catch Block:*
```
try {
File le = new File("example.txt");
FileReader reader = new FileReader( le);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
```

*Declaring in Method Signature:*


```
public void readFile(String lename) throws FileNotFoundException {
File le = new File( lename);
FileReader reader = new FileReader( le);
}
```

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());
}
}
```

# Order of Catch Block Evaluation:


1. *Speci c exceptions rst*: The Java compiler requires that speci c exceptions be caught before
general exceptions.
2. *Order matters*: The order of catch blocks matters. If a more general exception is caught before
a speci c exception, the speci c exception will be unreachable and result in a compiler error.
3. *Unreachable catch blocks*: If a catch block is unreachable due to the order of catch blocks, the
compiler will throw an error.

# 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:

# Java Exception Hierarchy:


- `Throwable` (root)
- `Error` (unchecked)
- `Exception` (checked)
- `RuntimeException` (unchecked)
- `NullPointerException`, `ArrayIndexOutOfBoundsException`, etc.
- Other checked exceptions (e.g., `IOException`, `SQLException`)

# 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`)

# When Exceptions Might Occur:


- Checked exceptions:
- When working with les or networks (e.g., `IOException`)
- When interacting with databases (e.g., `SQLException`)
- Unchecked exceptions:
- When accessing a null object reference (e.g., `NullPointerException`)
- When accessing an array index that is out of bounds (e.g.,
`ArrayIndexOutOfBoundsException`)
- When running out of memory (e.g., `OutOfMemoryError`)

# 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`:

# Writing Binary Data to a File:


```
import java.io.FileOutputStream;
import java.io.IOException;

public class BinaryFileWriter {


public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("binary le.bin")) {
// Write an integer
int intValue = 12345;
fos.write(intValue >> 24);
fos.write(intValue >> 16);
fos.write(intValue >> 8);
fos.write(intValue);

// Write a string as bytes


String str = "Hello, World!";
fos.write(str.getBytes());

// Write a boolean
boolean boolValue = true;
fos.write(boolValue ? 1 : 0);
} catch (IOException e) {
System.out.println("Error writing to le: " + e.getMessage());
}
}
}
```

# Importance of Handling Binary Files:


1. *Data Integrity*: Binary les require careful handling to ensure data integrity. Incorrectly writing
or reading binary data can result in corrupted or unusable data.
2. *Platform Independence*: Binary les can be platform-dependent, meaning that data written on
one platform may not be readable on another. This can be due to differences in byte order or data
type sizes.
3. *Security*: Binary les can pose security risks if not handled properly. For example, if sensitive
data is written to a binary le without proper encryption, it may be vulnerable to unauthorized
access.

# 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`:

# Reading and Writing Files with Exception Handling:


```
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWrite {


public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";

try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));


BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}

System.out.println("File copied successfully!");

} 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:

# Handling Multiple Exceptions:


```
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class MultipleExceptions {


public static void main(String[] args) {
try {
// File reading
BufferedReader reader = new BufferedReader(new FileReader("nonexistent le.txt"));
String line = reader.readLine();
reader.close();

// Arithmetic operation
int x = 10 / 0;

// Array index out of bounds


int[] array = new int[5];
System.out.println(array[10]);

} 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:

# Handling Multiple Exceptions Separately:


```
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class MultipleExceptions {


public static void main(String[] args) {
try {
// File reading
BufferedReader reader = new BufferedReader(new FileReader("nonexistent le.txt"));
String line = reader.readLine();
reader.close();
} catch (IOException e) {
fi
fi
fi
fi
Assignment 4
System.out.println("An I/O error occurred: " + e.getMessage());
}

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy