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

Unit Four

unit four

Uploaded by

ashwini bhosale
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit Four

unit four

Uploaded by

ashwini bhosale
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

4.

1 Exception Types
In Java, exceptions are events that disrupt the normal flow of a program. They are categorized
as:
1. Checked Exceptions: These are exceptions checked at compile time. Examples
include IOException, SQLException, and FileNotFoundException.
o Example: Trying to open a file that doesn’t exist will throw a
FileNotFoundException.
Example:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("nonexistentfile.txt");
FileReader fr = new FileReader(file); // May throw FileNotFoundException
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
2. Unchecked Exceptions (Runtime Exceptions): These exceptions occur during the
runtime and are not checked at compile time. Examples include
NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
o Example: Dividing by zero will throw an ArithmeticException.
Example:
public class UncheckedExceptionExample {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}
}
}
3. Error: Errors are serious issues that a program should not try to handle, such as
OutOfMemoryError, StackOverflowError.
o Example: Running a deep recursion may throw a StackOverflowError.

4.2 Using Try Catch and Multiple Catch - Nested try, throw, throws, and finally
Try-Catch Block
A try block is used to enclose the code that might throw an exception. The catch block
catches and handles the exception.
 Example: Catching an ArithmeticException and ArrayIndexOutOfBoundsException.
Example:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int arr[] = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
int result = 10 / 0; // Throws ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
}
}
}
Nested Try Block
A try block inside another try block is called a nested try block.
 Example: Nested try to handle multiple scenarios.
Example:
public class NestedTryExample {
public static void main(String[] args) {
try {
try {
int data = 50 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
}
int arr[] = new int[5];
arr[7] = 10; // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error: " + e.getMessage());
}
}
}
Throw and Throws
 Throw: Manually throw an exception using the throw keyword.
 Throws: Indicates that a method may throw exceptions.
 Example: Using throw and throws.
Example:
public class ThrowThrowsExample {
public static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
} else {
System.out.println("Result: " + (a / b));
}
}

public static void main(String[] args) {


try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
Finally Block
The finally block is always executed after the try and catch blocks, whether an exception
occurs or not.
 Example: Using the finally block.
public class FinallyExample {
public static void main(String[] args) {
try {
int data = 50 / 0; // Exception occurs
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block always executes.");
}
}
}

4.3 Creating User-Defined Exceptions, Built-in Exceptions


User-Defined Exception
You can create your own exceptions by extending the Exception class.
 Example: Creating and throwing a custom exception.

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

public class UserDefinedExceptionExample {


public static void validate(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Not eligible to vote");
} else {
System.out.println("Welcome to vote");
}
}

public static void main(String[] args) {


try {
validate(16);
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
Built-in Exception
Java provides a set of built-in exceptions like ArithmeticException, NullPointerException,
etc.
 Example: Handling a NullPointerException.
public class BuiltInExceptionExample {
public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length()); // Throws NullPointerException
} catch (NullPointerException e) {
System.out.println("Null value: " + e.getMessage());
}
}
}

File Handling
File handling in Java allows you to read and write data to files.

4.4 Stream - Byte Stream Classes and Character Stream Classes


Java I/O Streams
Java provides two major types of streams for handling input and output operations:
1. Byte Stream:
o Used for reading and writing binary data (e.g., images, audio files).
o The main classes are InputStream and OutputStream.
o Byte streams handle raw 8-bit binary data and are suitable for handling file
types like images and binary files.
o Common byte stream classes:
 FileInputStream
 FileOutputStream
2. Character Stream:
o Designed for reading and writing text data (characters) encoded in formats like
UTF-8 or ASCII.
o The main classes are Reader and Writer.
o Character streams are designed for handling text files and use Unicode
characters (16-bit).
o Common character stream classes:
 FileReader
 FileWriter
Byte Stream Example (Reading/Writing Binary Data)
 Example: Writing and reading bytes using FileOutputStream and FileInputStream.
java
Copy code
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteStreamExample {


public static void main(String[] args) {
try {
// Writing bytes to a file
FileOutputStream fos = new FileOutputStream("byteFile.txt");
String text = "This is a byte stream example";
fos.write(text.getBytes()); // Writing string as bytes
fos.close();
// Reading bytes from a file
FileInputStream fis = new FileInputStream("byteFile.txt");
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i); // Converting byte to char
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:

o The program first writes a string to a file as a sequence of bytes using
FileOutputStream.
o Then, it reads the file byte-by-byte using FileInputStream and converts each
byte back to a character.
Character Stream Example (Reading/Writing Text Data)
 Example: Writing and reading characters using FileWriter and FileReader.
java
Copy code
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamExample {


public static void main(String[] args) {
try {
// Writing characters to a file
FileWriter fw = new FileWriter("characterFile.txt");
fw.write("This is a character stream example");
fw.close();

// Reading characters from a file


FileReader fr = new FileReader("characterFile.txt");
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i); // Reading character-by-character
}
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
 Explanation:
o The program writes a string to a file as characters using FileWriter and reads
the file back character-by-character using FileReader.

4.5 File IO Basics


In Java, file input and output (I/O) operations are performed using the classes of the java.io
package. Java's file I/O is based on streams, and it offers various classes for handling file
operations efficiently.
Basic File I/O Operations
1. Creating a File: Using the File class, we can create a new file.
2. Reading a File: Using input stream classes (FileInputStream for byte data, FileReader
for character data) to read data from a file.
3. Writing to a File: Using output stream classes (FileOutputStream for byte data,
FileWriter for character data) to write data to a file.
4. Closing Streams: Streams must be closed after performing I/O operations to release
system resources.
 File Class: Java provides the File class to represent a file or directory path. It is used
for file operations like creation, deletion, and querying file properties.

4.6 File Operations - Creating, Reading, and Writing Files


1. Creating a File
The File class is used to create a new file. If the file already exists, it will not be created
again.
 Example: Creating a file using the File class.
import java.io.File;
import java.io.IOException;
public class FileCreationExample {
public static void main(String[] args) {
File file = new File("newfile.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
 Explanation:
o This code creates a new file named "newfile.txt". If the file already exists, it
will display a message saying the file already exists.
2. Reading a File
There are two common ways to read files:
1. Using Byte Stream (FileInputStream): Reads raw byte data.
2. Using Character Stream (FileReader): Reads text data.
Reading a File Using Byte Stream
 Example: Reading a file byte-by-byte.
import java.io.FileInputStream;
import java.io.IOException;
public class ByteFileReadExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i); // Print the bytes as characters
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
o This program reads a file named "example.txt" byte-by-byte and prints the
data. Each byte is converted to a character for readable output.
Reading a File Using Character Stream
 Example: Reading a file character-by-character.
import java.io.FileReader;
import java.io.IOException;
public class CharFileReadExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("example.txt");
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i); // Print the characters
}
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
 Explanation:
o This code reads the file "example.txt" character-by-character and prints each
character to the console.
3. Writing to a File
Similar to reading, writing to a file can be done using:
1. Byte Stream (FileOutputStream): Writes raw bytes.
2. Character Stream (FileWriter): Writes text data.
Writing to a File Using Byte Stream
 Example: Writing bytes to a file.
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteFileWriteExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("outputByteFile.txt");
String text = "Hello, this is byte stream data!";
fos.write(text.getBytes()); // Convert string to bytes
fos.close();
System.out.println("File written successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:

o This program writes a string to a file named "outputByteFile.txt" using
FileOutputStream. The string is converted into bytes before writing.
Writing to a File Using Character Stream
 Example: Writing characters to a file.
import java.io.FileWriter;
import java.io.IOException;
public class CharFileWriteExample {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("outputCharFile.txt");
fw.write("Hello, this is character stream data!");
fw.close();
System.out.println("File written successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
 Explanation:
o This code writes a string to a file named "outputCharFile.txt" using FileWriter.
Since FileWriter works with characters, no conversion to bytes is needed.

Summary
 Byte Stream: Used for handling raw binary data. Classes like FileInputStream and
FileOutputStream help read/write bytes to/from files.
 Character Stream: Designed for handling text files. Classes like FileReader and
FileWriter help read/write characters to/from files.
 File Operations:
o Creating Files: Using the File class to create new files.
o Reading Files: Using FileInputStream for byte streams and FileReader for
character streams.
o Writing Files: Using FileOutputStream for byte streams and FileWriter for
character streams.

Unit Five: https://www.javatpoint.com/java-awt, https://www.javatpoint.com/java-awt


Unit Four : https://www.javatpoint.com/exception-handling-in-java
Unit Four : File handling in java: https://www.geeksforgeeks.org/file-handling-in-java/

You might also like